Skip to main contentSkip to solution

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

✅ Correct Option: 4

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.

Keyboard Shortcuts

  • Left arrow: Previous question
  • Right arrow: Next question
  • S key: Jump to solution
  • Q key: Jump to question