Searching

Finding a roll number in an unsorted register means reading it name by name; finding a word in a dictionary means opening it near the middle and discarding half the book at every step. Those are the two searching methods of the syllabus — linear search and binary search — and the difference between them is the difference between checking everything and using order. This chapter traces both, counts how many comparisons each needs in the best and worst cases, and closes with hashing, which aims to find an element in a single step. Expect questions that ask for the elements examined in a binary search, in order, and for worst-case counts.
Overview

Linear Search

1 min read · 1 part

A linear search that returns the position of the first match, or −1 if there is none. print(search([5, 3, 5, 8], 5), search([5, 3, 5, 8], 6)) prints 0 -1 — the second 5 is never reached:
def search(L, key):
for i in range(len(L)):
if L[i] == key:
return i
return -1

Linear search, also called sequential search, compares the key with each element of the list in turn, starting from the first, until it finds a match or reaches the end. It makes no…

Binary Search

2 min read · 5 parts
Binary search for 23 in [3, 8, 12, 17, 23, 31, 40]
firstlastmidElement at midDecision
0631723 > 17, so first = 4
4653123 < 31, so last = 4
44423found at index 4
⚠️ Integer division picks the left middle
With first = 4 and last = 5, mid is (4 + 5) // 2 = 4, not 4.5 and not 5. In an even-length range the left of the two middle elements is examined, and a trace that rounds up will name the wrong elements from that point on.
Linear and binary search compared
FeatureLinear searchBinary search
List must be sorted?NoYes
Best case1 comparison (first element)1 comparison (middle element)
Worst case, n elementsn comparisonsfloor(log₂ n) + 1 comparisons
Growthlinear in nlogarithmic in n

Binary search works only on a sorted list. It keeps two markers, first and last, around the part still to be searched, and repeatedly examines the middle element, mid = (first + last) // 2.…

Search by Hashing

1 min read · 2 parts

Hashing tries to find an element without comparing it against others at all. A hash function computes, from the element itself, the position in a hash table where it should be stored. A simple one is the remainder method: h(element) = element % size of the table. With a table of 10 slots, 34 goes to slot 4, 16 to slot 6 and 93 to slot 3; to search for 93, compute 93 % 10 = 3 and look in slot 3 directly. When two elements produce the same slot — 34 and 54 both give 4 — that is a collision, which has to be resolved by some further rule; a hash function that never produces a collision for a given set of elements is a perfect hash function.

Searching by hashing
  1. Take the element: 93
  2. Hash function: 93 % 10Remainder method, 10 slots
  3. Slot 3
  4. Look in slot 3 directlyNo comparison along the list
34 and 54 both give slot 4: a collision.

Hashing tries to find an element without comparing it against others at all. A hash function computes, from the element itself, the position in a hash table where it should be stored. A…

Choosing the Search Method

1 min read

The right search method depends on the data. For a short list, or one that is unsorted and searched only once, linear search is simplest and sorting first would cost more than it saves. For a large sorted list searched many times, binary search wins by a wide margin. If the list is unsorted and searched repeatedly, it can pay to sort once and then use binary search for every query, because the cost of sorting is spread over many searches. Hashing is the choice when searches must be as fast as possible and the key can be mapped to a position, as in a dictionary of names to phone numbers, but it gives no useful order and needs a plan for collisions. In Python, the in operator on a list does a linear search, the bisect module searches sorted lists by halving, and a dictionary uses hashing.

The right search method depends on the data. For a short list, or one that is unsorted and searched only once, linear search is simplest and sorting first would cost more than it saves. For…

Key takeaways

  • Linear search checks elements one by one, works on unsorted lists, and needs 1 comparison at best and n at worst.
  • Binary search needs a sorted list: compare with the middle, then keep only the half that can hold the key.
  • mid = (first + last) // 2; a smaller key sets last = mid − 1, a larger key sets first = mid + 1, and first > last means not found.
  • Binary search needs at most floor(log₂ n) + 1 comparisons: 5 for 31 elements, 10 for 1,000.
  • Hashing computes an element's slot directly, e.g. element % table size; two elements in one slot is a collision.

Practice questions (24)

Attempt each one before opening the answer. Every explanation names the tempting wrong option as well as the right one, because that is where marks are lost.

  1. Binary search is used to find 23 in the sorted list [3, 8, 12, 17, 23, 31, 40], with mid = (first + last) // 2. Which elements are compared with 23, in order?

    1. 17, 23
    2. 17, 31, 23
    3. 3, 8, 12, 17, 23
    4. 17, 40, 31, 23
    Show answer

    Answer: B — 17, 31, 23

    First mid is index 3, element 17; 23 is larger, so first = 4. Now mid = (4 + 6) // 2 = 5, element 31; 23 is smaller, so last = 4. Then mid = 4, element 23 — found after three comparisons. 17, 23 skips the middle of the right half and jumps straight to the key. The five-element sequence is what a linear search would do, and nothing in binary search ever looks at the last element first.
  2. What does this code print?
    def search(L, key):
    for i in range(len(L)):
    if L[i] == key:
    return i
    return -1
    print(search([5, 3, 5, 8], 5), search([5, 3, 5, 8], 6))

    1. 2 -1
    2. 1 -1
    3. 0 None
    4. 0 -1
    Show answer

    Answer: D — 0 -1

    The loop returns as soon as it finds the first match, which for 5 is at index 0; the 5 at index 2 is never reached. For 6 the loop ends without a match and the function returns -1. Answering 2 assumes the search continues to the last match, 1 counts positions from 1, and None would be returned only if the final return -1 were missing.
  3. What must be true of a list before binary search can be applied to it reliably?

    1. It must be sorted
    2. It must contain no duplicate values
    3. Its length must be a power of 2
    4. It must hold integers only
    Show answer

    Answer: A — It must be sorted

    Discarding a half is only safe if every element on one side of the middle is smaller and every element on the other side larger, and that is what sorting guarantees. Duplicates do not stop the method; it simply finds one of the equal values. Any length works, since integer division picks a middle every time, and strings sorted alphabetically can be searched just as well as numbers.
Show the other 21 questions
  1. What is the maximum number of comparisons binary search needs to decide whether a key is present in a sorted list of 31 elements?

    1. 31
    2. 16
    3. 5
    4. 6
    Show answer

    Answer: C — 5

    Each comparison leaves at most half of the remaining elements: 31, then 15, 7, 3 and 1, so after the fifth comparison nothing is left to examine — floor(log₂ 31) + 1 = 5. Thirty-one is the worst case of a linear search, the method that ignores order. 16 halves only once, and 6 adds an extra step that a range of 31 never needs.
  2. What is printed by the following code?
    L = [2, 4, 6, 8, 10, 12, 14]
    first, last, steps = 0, len(L) - 1, 0
    key = 5
    while first <= last:
    mid = (first + last) // 2
    steps += 1
    if L[mid] == key:
    break
    elif key < L[mid]:
    last = mid - 1
    else:
    first = mid + 1
    print(steps)

    1. 2
    2. 3
    3. 7
    4. 4
    Show answer

    Answer: B — 3

    Step 1: mid = 3, element 8; 5 < 8, so last = 2. Step 2: mid = 1, element 4; 5 > 4, so first = 2. Step 3: mid = 2, element 6; 5 < 6, so last = 1. Now first (2) exceeds last (1), the loop ends with the key absent, and steps is 3. Stopping at 2 forgets that the range [2, 2] still has to be examined, and 7 counts every element as a linear search would.
  3. A linear search is run on a list of n elements for a key that is not in the list. How many comparisons does it make?

    1. 1
    2. n / 2
    3. n
    4. about log₂ n
    Show answer

    Answer: C — n

    Linear search can only conclude that the key is absent after comparing it with every element, so an unsuccessful search costs all n comparisons — the worst case. One comparison is the best case, when the key happens to be first. n / 2 is the average for a key that is present, and log₂ n belongs to binary search on a sorted list.
  4. Assertion (A): Linear search can be used on a list whose elements are in no particular order. Reason (R): In the worst case, linear search compares the key with every element of the list.

    1. Both A and R are true, and R is the correct explanation of A
    2. Both A and R are true, but R is not the correct explanation of A
    3. A is true, but R is false
    4. A is false, but R is true
    Show answer

    Answer: B — Both A and R are true, but R is not the correct explanation of A

    Both statements are true, but R describes the cost of linear search, not why it works on unordered data. It works on any list because it never uses order to skip an element — every element is examined in turn until a match is found. Choosing "R explains A" links two true facts that happen to be about the same method; the paper sets exactly this pairing to test whether the link is real.
  5. Using linear search from the first element, how many comparisons are needed to find 9 in the list [4, 7, 9, 2]?

    1. 2
    2. 4
    3. 1
    4. 3
    Show answer

    Answer: D — 3

    The key is compared with 4, then 7, then 9, where it matches and the search stops: three comparisons. Two is the zero-based index of 9, a position rather than a count. Four would be needed only if the key were last or absent, and one only if it were the first element.
  6. Linear search examines the elements of a list:

    1. One by one in sequence until the key is found or the list ends
    2. By halving the list each time
    3. Only the middle element
    4. In a random order only
    Show answer

    Answer: A — One by one in sequence until the key is found or the list ends

    Linear search goes through the elements in order. Halving belongs to binary search.
  7. Binary search repeatedly:

    1. Divides the sorted search range in half
    2. Checks each element in order
    3. Sorts the list first each time
    4. Checks only the last element
    Show answer

    Answer: A — Divides the sorted search range in half

    It compares the key with the middle and discards half of the range. Checking each element in order is linear search.
  8. Which technique finds an element in constant time on average by computing its position from the key?

    1. Hashing
    2. Linear search
    3. Bubble sort
    4. Insertion sort
    Show answer

    Answer: A — Hashing

    A hash function maps the key straight to an index. Linear search must scan elements, and the sorts do not search.
  9. A hash function maps a key to:

    1. A position (index) in the hash table
    2. A file name
    3. A network address
    4. A random colour
    Show answer

    Answer: A — A position (index) in the hash table

    The output of the hash function is the slot where the key is stored. The other options are unrelated.
  10. What is the output of the following code?
    L = [2, 5, 8, 12, 16, 23, 38]
    lo, hi, steps = 0, len(L) - 1, 0
    while lo <= hi:
    mid = (lo + hi) // 2
    steps += 1
    if L[mid] == 23:
    break
    elif L[mid] < 23:
    lo = mid + 1
    else:
    hi = mid - 1
    print(mid, steps)

    1. 3 1
    2. 5 2
    3. 6 3
    4. 5 5
    Show answer

    Answer: B — 5 2

    The first mid is index 3 (12 < 23), so lo becomes 4; the next mid is 5 and L[5] is 23, found in 2 steps: 5 2. "3 1" stops at the first mid and "6 3" overshoots.
  11. What is the output of the following code?
    size = 5
    table = [None] * size
    for k in [12, 7, 22]:
    table[k % size] = k
    print(table)

    1. [None, None, 12, 7, 22]
    2. [None, None, 22, None, None]
    3. [12, 7, 22, None, None]
    4. [None, None, 7, None, None]
    Show answer

    Answer: B — [None, None, 22, None, None]

    All three keys give k % 5 = 2, so each overwrites the previous one and only 22 remains: [None, None, 22, None, None]. This overwriting is a collision, and "[12, 7, 22, None, None]" ignores the hash function.
  12. With the hash function h(k) = k % 10, the key 47 is stored at index:

    1. 7
    2. 4
    3. 47
    4. 10
    Show answer

    Answer: A — 7

    47 % 10 leaves the remainder 7. 4 is the quotient and 47 would need a table of 48 slots.
  13. Assertion (A): Binary search can be applied only on a sorted list.
    Reason (R): The decision to discard half of the range depends on the order of the elements.
    Choose the correct option:

    1. Both A and R are true and R is the correct explanation of A
    2. Both A and R are true but R is not the correct explanation of A
    3. A is true but R is false
    4. A is false but R is true
    Show answer

    Answer: A — Both A and R are true and R is the correct explanation of A

    Without order, the half discarded might contain the key, which R implies. Option 2 is wrong.
  14. Consider the following statements:
    A. Linear search can be applied to an unsorted list.
    B. Binary search requires a sorted list.
    C. For a large sorted list, linear search is faster than binary search.
    D. Hashing can find an element in constant time on average.
    Choose the correct answer:

    1. A, B and D only
    2. A and C only
    3. B, C and D only
    4. A, B, C and D
    Show answer

    Answer: A — A, B and D only

    A, B and D are correct. C is false because binary search needs far fewer comparisons on a large sorted list, so option 4 is the trap.
  15. What is the output of the following code?
    def find(L, k):
    for i in range(len(L)):
    if L[i] == k:
    return i
    return -1
    print(find([4, 9, 4], 4), find([4, 9], 7))

    1. 2 -1
    2. 0 -1
    3. 0 0
    4. -1 -1
    Show answer

    Answer: B — 0 -1

    The first call returns the first index 0 at once, and the second finds nothing and returns -1: 0 -1. "2 -1" reports the last occurrence, and "0 0" misses the failure value.
  16. What is the output of the following code?
    L = [1, 3, 5, 7, 9]
    lo, hi, steps = 0, 4, 0
    while lo <= hi:
    mid = (lo + hi) // 2
    steps += 1
    if L[mid] == 4:
    break
    elif L[mid] < 4:
    lo = mid + 1
    else:
    hi = mid - 1
    print(steps, lo, hi)

    1. 2 2 1
    2. 3 2 1
    3. 5 0 4
    4. 3 0 4
    Show answer

    Answer: B — 3 2 1

    The mids are 2, 0 and 1, which makes three steps, and the loop ends with lo = 2 and hi = 1 because 4 is absent: 3 2 1. "5 0 4" is the linear count of the whole list.
  17. The maximum number of comparisons binary search needs on a sorted list of 100 elements is:

    1. 7
    2. 100
    3. 50
    4. 10
    Show answer

    Answer: A — 7

    The range halves each time and 2 to the power 7 is 128, which is at least 100, so 7 comparisons suffice. 100 is the linear worst case and 50 is half of it.
  18. What is the output of the following code?
    L = [7, 3, 9, 1]
    c = 0
    for x in L:
    c += 1
    if x == 1:
    break
    print(c)

    1. 1
    2. 3
    3. 4
    4. 5
    Show answer

    Answer: C — 4

    The key 1 is the last element, so linear search makes a comparison for every element: 4. 5 counts an extra comparison and 1 assumes the first element matches.
  19. What is the output of the following code?
    table = [[] for _ in range(4)]
    for k in [5, 9, 13, 6]:
    table[k % 4].append(k)
    print(table)

    1. [[], [5, 9, 13], [6], []]
    2. [[5], [9], [13], [6]]
    3. [[], [5], [9, 13], [6]]
    4. [[], [5, 9], [13, 6], []]
    Show answer

    Answer: A — [[], [5, 9, 13], [6], []]

    Keys 5, 9 and 13 all give remainder 1 and chain together, and 6 gives 2, so the table is [[], [5, 9, 13], [6], []]. "[[5], [9], [13], [6]]" ignores the hash function.
  20. Assertion (A): A hash table gives nearly constant search time on average.
    Reason (R): The hash function computes the index directly from the key, so no scanning of the elements is needed.
    Choose the correct option:

    1. Both A and R are true and R is the correct explanation of A
    2. Both A and R are true but R is not the correct explanation of A
    3. A is true but R is false
    4. A is false but R is true
    Show answer

    Answer: A — Both A and R are true and R is the correct explanation of A

    Direct computation of the slot avoids scanning, which R states. Option 2 is wrong.
  21. The maximum comparisons binary search needs on a sorted list of 15 elements is:

    1. 4
    2. 15
    3. 8
    4. 3
    Show answer

    Answer: A — 4

    Halving 15 gives ranges of 15, 7, 3 and 1, which is 4 comparisons. 3 stops one step too early and 8 is about half of 15.