CS FundamentalsVery hardProduct-company placement · GATE CS

Which loop invariant lets you prove this binary search correct for a sorted list a?

Which loop invariant lets you prove this binary search correct for a sorted list a?
lo, hi = 0, len(a) - 1
while lo <= hi:
    mid = (lo + hi) // 2
    if a[mid] < t: lo = mid + 1
    elif a[mid] > t: hi = mid - 1
    else: return mid
return -1
  1. A. lo < hi throughout the loop
  2. B. a[lo] ≤ t ≤ a[hi] throughout the loop
  3. C. If t occurs in a, it occurs in a[lo..hi]
  4. D. mid always points to t's position

Correct answer: C. If t occurs in a, it occurs in a[lo..hi]

Each update discards only positions that cannot hold t because the list is sorted, so 'if t is in a, it is in a[lo..hi]' is preserved. When lo > hi the range is empty, proving -1 is correct. a[lo] ≤ t ≤ a[hi] fails when t is absent.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic