0% found this document useful (0 votes)
8 views

A4 Solutions – Binary search algorithm

The document contains a Python implementation of the binary search algorithm, which searches for a specified item in a sorted list. It uses a while loop to repeatedly narrow down the search range until the item is found or the range is exhausted. Key variables include 'index', 'first', 'last', 'found', and 'midpoint', with the algorithm returning the index of the found item or -1 if not found.

Uploaded by

wba59179
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

A4 Solutions – Binary search algorithm

The document contains a Python implementation of the binary search algorithm, which searches for a specified item in a sorted list. It uses a while loop to repeatedly narrow down the search range until the item is found or the range is exhausted. Key variables include 'index', 'first', 'last', 'found', and 'midpoint', with the algorithm returning the index of the found item or -1 if not found.

Uploaded by

wba59179
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

1 def binary_search(items, search_item):

#
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

index first last found midpoint items[midpoint]

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

You might also like