Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Binary search for x in a sorted int array (C++):

Problem: Binary search for x in a sorted int array (C++):
int lo = 0, hi = n - 1;
while (lo <= hi) {
    int mid = (lo + hi) / 2;      // line 3
    if (a[mid] == x) return mid;
    if (a[mid] < x) lo = mid;     // line 5
    else hi = mid - 1;
}
return -1;
Which line contains the bug that can cause an infinite loop?
  1. A. Line 3 – (lo + hi) / 2 always loops forever
  2. B. Line 1 – hi must be n
  3. C. There is no bug
  4. D. Line 5 – it must be lo = mid + 1

Correct answer: D. Line 5 – it must be lo = mid + 1

With lo = mid, when hi = lo + 1 and a[lo] < x, mid stays equal to lo forever. (lo + hi) / 2 can overflow only for indices near 2³¹ – worth fixing with lo + (hi − lo)/2, but it is not what causes the loop here. hi = n − 1 matches the inclusive loop condition.

More Coding Interview Problems questions

Exams that ask this topic