GATE Computer ScienceHardGATE CS

Binary search (lo = 0, hi = n − 1, mid = ⌊(lo + hi)/2⌋; each loop iteration compares a[mid] once and ends the search on equality) is run once for each of the 20 elements of a sorted array of n = 20 distinct elements, always with the element present. What is the total number of loop iterations over all 20 searches?

  1. A. 71
  2. B. 74
  3. C. 80
  4. D. 65

Correct answer: B. 74

The iteration count for an element equals its depth plus one in the implicit binary search tree. The tree has levels with 1, 2, 4, 8 and 5 nodes, so the total is 1·1 + 2·2 + 4·3 + 8·4 + 5·5 = 74.

More Programming and Data Structures (GATE) questions

Exams that ask this topic