Lesson 12.10
Let's put the module into one tool: sorting, a fast search and a simple search, plus a check that the data really is sorted.
def binary_search(numbers, target):
left, right = 0, len(numbers) - 1
while left <= right:
mid = (left + right) // 2
if numbers[mid] == target:
return mid
elif numbers[mid] < target:
left = ... # the right half
else:
right = ... # the left half
return -1
The check gives the list numbers and the number target. Write:
bubble_sort(numbers) — sorts a copy and returns it;linear_search(numbers, target) — the index of the first match or -1;binary_search(numbers, target) — the same, but halving, works on a sorted list.The program sorts the list and prints three lines:
Sorted: <list>
Linear: <index>
Binary: <index>
Both searches must give the same answer — that is the check: the fast way agrees with the slow one.
Three functions: bubble_sort (sorts a copy), linear_search and
binary_search.
The order of work: sort first, then search in the sorted list. Both searches must give the same answer — that is the check.