AmbifulWorksheets
Cheat sheet
CBSE · Class 12 · Computer Science

Searching

Linear search, binary search with its mid points as the textbook codes it, the comparisons each makes, and hashing by the remainder method with collisions.

Key ideas

Remember

Linear searchcomparisons = the position of the key, or n if it is missing
Binary searchL = [4, 9, 15, 22, 30, 41, 56], key 41: mid 3 (22 is smaller), then mid 5 (41): 2 comparisons
Most comparisons, n itemsthe whole part of log2 n, plus 1: 7 items → 3, 100 → 7, 1,000 → 10
Hash functionh(key) = key % size: 47 % 10 = 7, and 57 % 10 = 7 too, a collision
Comparing the twolinear: up to n; binary: up to about log2 n, but only on a sorted list

Watch out

Worked example

What does this print?
L = [7, 17, 21, 27, 33, 36, 47, 71, 81, 83, 87, 98]
key = 87
first, last = 0, len(L) - 1
count = 0
pos = None
while first <= last:
    mid = (first + last) // 2
    count = count + 1
    if L[mid] == key:
        pos = mid
        break
    elif L[mid] > key:
        last = mid - 1
    else:
        first = mid + 1
print(pos, count)

Working: pos stays None when the key is not found; count is the number of passes

Answer: 10 3