Data Structures and Algorithms
Which is a prerequisite for using binary search, which compares the target with the middle element and halves the search range each time?
- AThe number of data items must be a power of two
- BThe data must be sorted by key
- CThe data must not contain duplicate values
Show answer and explanation
Answer: B. The data must be sorted by key
Binary search uses the result of comparing the target with the middle element to decide whether the target lies in the first or second half, and halves the range. That conclusion holds only because the data is sorted, so binary search cannot be used on an unsorted array. The number of items does not need to be a power of two; choosing the middle as (low + high) ÷ 2 rounded down works for any size. Duplicates are also fine: one of the matching values is found (finding the first occurrence takes a small extra step).
- A. Choosing the middle by rounding down works for any number of items.
- B. Correct. Because the data is sorted, a comparison with the middle element tells you which half to keep.
- C. Search still works with duplicates; one of the matching values is found.