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
lowandhigh(they start at 0 and at the last one). In each turn takemiddle = (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: iorNot found, thenBinary comparisons: bandLinear comparisons: l. The linear comparisons are the position + 1 if found, or the size of the list if not.
2 5 8 12 16 23 38 56 72 91
23
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