Given below is the Binary Search function to find an element in a list of elements in ascending order. Find the missing statement 1 and 2.
def binarySearch(list, key):
first = 0
last = len(list) - 1
while(first<=list):
mid=(first+last)//2
if(list[mid]= = key:
return mid
elif key > list[mid]:
___________ # Statement 1
elif key < list[mid]:
__________ # Statement 2
return -1
Given below is the Binary Search function to find an element in a list of elements in ascending order. Find the missing statement 1 and 2.
def binarySearch(list, key):
first = 0
last = len(list) - 1
while(first<=list):
mid=(first+last)//2
if(list[mid]= = key:
return mid
elif key > list[mid]:
___________ # Statement 1
elif key < list[mid]:
__________ # Statement 2
return -1
Solution
In an ascending list, if key > list[mid], the key can only lie in the right half. So the search must move past mid: first = mid + 1 (Statement 1).
If key < list[mid], the key lies in the left half, so last = mid - 1 (Statement 2).
Option 1: the two statements are swapped, which would search the wrong half.
Option 2: last = mid + 1 and first = mid - 1 move the bounds in the wrong direction, so the search range never narrows correctly.
Option 3: first = mid and last = mid do not exclude mid, which is already checked, and the loop can run forever when first and last are adjacent.
Related questions:
2026: 26 May Shift 1
2026: 23 May Shift 2
2026: 24 May Shift 1