Binary search in a list of subjects (Python)
🧩 Syntax:
book = [ "Archaeology", "Art", "Biology", "Chemistry",
"Computing", "English", "French", "Geography",
"History", "Maths", "Psychology"]
found = False # This is a flag - is it found or not?
left = 0 # Set left to 0 (first item in the list - Archaeology)
right = len(book) - 1 # Set right to the length of the list minus one (last item in the list)
find = "Maths"
#Repeat the following until item found, or you have check every item in the list
while found == False and left<=right:
mid = (left + right) // 2 # Calculates the midpoint
if book[mid] == find: # Check does the item we're looking at == search item
found = True # If it is, set found to True - we've found our search item!
index = mid
else:
# If not found, move the left or right pointer to the midpoint
# Depending on what side of the list we want to search next
if find > book[mid]:
left = mid + 1
else:
right = mid - 1
# Return to the while loop and re-check the conditions
# Continue repeating until item found or all items checked
# Output if the item is found or not
if found:
print("Item successfully found at position", index)
else:
print("Search term not found.")