| 1 | # assume L is already sorted |
2 | def binary_search(L, target): |
3 | left_idx = 0 # inclusive |
4 | right_idx = len(L) # exclusive |
5 | |
6 | # keep splitting our list in half, until |
7 | # it's length is <= 1 |
8 | while right_idx - left_idx > 1: |
9 | mid_idx = (right_idx + left_idx) // 2 |
10 | mid = L[mid_idx] |
11 | |
12 | # throw away left or right half? |
13 | if target >= mid: |
14 | left_idx = mid_idx |
15 | else: |
16 | right_idx = mid_idx |
17 | |
18 | # did we cut down to a list of length 1 containing target? |
19 | return right_idx > left_idx and L[left_idx] == target |
20 | |
21 | L = [1, 2, 9, 42, 60, 70, 80, 99] |
22 | found = binary_search(L, 80) |
23 | print(found) |