Data Structures and Algorithms

A binary search is performed on 1,000 distinct values sorted in ascending order. If one comparison tells you whether the values are equal, smaller or larger, what is the maximum number of comparisons, counting both successful and unsuccessful searches?

  1. A10
  2. B32
  3. C500
Show answer and explanation

Answer: A. 10

Each comparison roughly halves the search range, and 2¹⁰ = 1024 ≥ 1000, so the range is used up after at most 10 comparisons (⌊log₂ 1000⌋ + 1 = 10). The complexity is O(log n), and even 1,000,000 values need at most 20 comparisons. 32 corresponds to √1000 ≈ 31.6, and 500 is close to the average for a linear search (about n/2). Keep in mind, though, that binary search needs sorted data, and sorting itself costs O(n log n).

  • A. Correct. 2¹⁰ = 1024 ≥ 1000, so at most 10 comparisons are needed.
  • B. This corresponds to √1000 and has nothing to do with binary search.
  • C. This is close to the average number of comparisons for a linear search.
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. 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?
  2. 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?
  3. 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?
  4. 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?
  5. 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?