ProgrammingHardCapgemini · Infosys pattern

The array holds {1, 3, 5, 7, 9, 11, 13, 15, 17} (indexed from 0). What is printed? (/ is integer division.)

The array holds {1, 3, 5, 7, 9, 11, 13, 15, 17} (indexed from 0). What is printed? (/ is integer division.)
Integer low = 0, high = 8, mid, steps = 0, key = 4
while (low <= high)
    mid = (low + high) / 2
    steps = steps + 1
    if (arr[mid] == key)
        break
    else if (arr[mid] < key)
        low = mid + 1
    else
        high = mid - 1
    end if
end while
Print steps, low
  1. A. 4 2
  2. B. 3 2
  3. C. 3 1
  4. D. 2 2

Correct answer: B. 3 2

mid = 4 (9 > 4) so high = 3. mid = 1 (3 < 4) so low = 2. mid = 2 (5 > 4) so high = 1. Now low > high and the search fails after 3 steps. low = 2 is where 4 would be inserted.

More Pseudocode and Code Tracing questions

Exams that ask this topic