These questions follow Searching. Use this sorted list of community centre card numbers throughout, and count comparisons by hand before you count them in code:

cards = [102, 118, 134, 155, 167, 189, 203, 221, 240]

By hand

  1. Trace a binary search for 203. Write down low, high, middle, and the value examined at each step, and say how many comparisons it took.
  2. Trace a binary search for 130, which is not there. How does the loop end, and how many comparisons were made?
  3. A linear search for 240 in this list takes how many comparisons? For 102? For a number that is absent? Which of the three is the worst case, and does the same answer hold for binary search?

In code

  1. Write linear_search(values, target) returning the index or -1, with a docstring that states its precondition.
  2. Write binary_search(values, target) with the same signature. State the precondition in the docstring, and explain in one sentence why low <= high and middle + 1 matter.
  3. Find the fault. This binary search never terminates for some inputs. Why?
    while low <= high:
        middle = (low + high) // 2
        if values[middle] == target:
            return middle
        elif values[middle] < target:
            low = middle
        else:
            high = middle
  4. Write find_by_card(members, card) that searches a list of Member objects (each with name and card) and returns the object or None. Why does this one have to be a linear search, as written?
  5. Write all_positions(values, target), returning every index where the target appears. Test it on [2, 5, 2, 9, 2].
  6. Judgement. Run binary_search on the same numbers shuffled into arrival order and search for 240. Report what happens, and write the sentence you would put in a code review.

Answers

Curriculum connection

A1.1

demonstrate the ability to use integer division and resultant remainders in computer programs;

Link to original

A3.2

create linear and binary search algorithms to find data in an array;

Link to original

C2.1

demonstrate the ability to analyse a precondition (i.e., starting state) and a postcondition (i.e., ending state) in an algorithm;

Link to original

C2.2

compare the efficiency of linear and binary searches, using run times and computational complexity analysis (e.g., to analyse the number of statements executed, the number of iterations of a loop, or the number of comparisons performed);

Link to original