Data Structures and Algorithms

A binary search looks for 38 in the ascending array a[0] to a[9] = 3, 8, 12, 17, 23, 31, 38, 45, 52, 60. The search range starts with lo = 0 and hi = 9, and the middle position is (lo + hi) ÷ 2 rounded down. Which lists, in order, the elements compared with 38?

  1. A23, 38
  2. B31, 52, 45, 38
  3. C23, 45, 31, 38
Show answer and explanation

Answer: C. 23, 45, 31, 38

First, (0 + 9) ÷ 2 = 4, so 38 is compared with a[4] = 23; 38 is larger, so lo = 5. Next, (5 + 9) ÷ 2 = 7, so it is compared with a[7] = 45; 38 is smaller, so hi = 6. Then (5 + 6) ÷ 2 = 5 gives a[5] = 31, so lo = 6, and finally a[6] = 38 matches. That is 4 comparisons, the maximum for 10 elements, ⌊log₂ 10⌋ + 1 = 4. The order 31, 52, 45, 38 results from rounding the middle up, which is not the rule given in the question.

  • A. After comparing with 23, the next comparison is with a[7] = 45, the middle of the remaining range a[5] to a[9].
  • B. This is the order when the middle is rounded up, which differs from the rule in the question.
  • C. Correct. It compares a[4], a[7], a[5] and a[6] in turn and finds the value on the fourth comparison.
Practice this topic Back to topic

Related calculators

Books on Data Structures and Algorithms Ad

As an Amazon Associate I earn from qualifying purchases.

More Data Structures and Algorithms questions

  1. The array 5, 3, 8, 1, 4 is sorted in ascending order with bubble sort. What is the array after one pass, in which neighboring elements are compared from the front to the end and swapped whenever the left one is larger?
  2. The array 29, 10, 14, 37, 13 is sorted in ascending order with selection sort, which finds the minimum of the unsorted part and swaps it with the first element of the unsorted part. What is the array after this step has been done twice?
  3. An array of 10 elements is sorted in ascending order with insertion sort. Each element from the second one on is taken out and compared with the elements to its left, starting with its left neighbor, until an element less than or equal to it is found or the front is reached. How many comparisons are made when the array is already in ascending order, and when it is in descending order?
  4. Which sorting algorithm is O(n log n) even in the worst case and sorts with almost no extra memory such as a work array?
  5. The (name, score) records (A, 80), (B, 70), (C, 80), (D, 70) are in this order. If they are sorted by score in ascending order with a stable sort, in what order do the names appear?