A4 Solutions – Binary search algorithm
A4 Solutions – Binary search algorithm
#
2 index = -1
3 first = 0
4 last = len(items) - 1
5 found = False
#
#
6 while first <= last and found == False:
#
7 midpoint = (first + last) // 2
#
8 if items[midpoint] == search_item:
9 index = midpoint
10 found = True
11 elif items[midpoint] < search_item:
12 first = midpoint + 1 #
13 else:
14 last = midpoint - 1 #
15 return index
found
Boolean.
False
True
False
False
midpoint
An index needs to be a whole number and floor division ignores the part of the number after the
decimal point. Using floor division in this algorithm means that if the midpoint is between two items,
the middle-left item will be the midpoint.
items
search_item
2 -1
3 0
4 7
5 False
6 True
7 3
8 Olivia False
11 Olivia True
12 4
6 True
7 5
8 Reg False
11 Reg False
14 4
6 True
7 4
8 True
9 4
10 True
6 False