Complexity and efficiency · 8 / 15 Exercise Hard

Binary search counting steps

Objective

Create a Python program that performs a binary search in a sorted list and compares how many steps it needs against linear search. Binary search is O(log n): it discards half at each step.

Instructions

  • Read a line with integers sorted from lowest to highest and without duplicates, and then a line with the integer to search for.
  • Keep the indexes low and high (they start at 0 and at the last one). In each turn take middle = (low + high) // 2, count one comparison and decide whether you found it, or you go on to the right (low = middle + 1) or to the left (high = middle - 1).
  • Show Position: i or Not found, then Binary comparisons: b and Linear comparisons: l. The linear comparisons are the position + 1 if found, or the size of the list if not.
Input
2 5 8 12 16 23 38 56 72 91
23
Output
Position: 5
Binary comparisons: 3
Linear comparisons: 6

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise