6.0k views
3 votes
What is the worst possible number of comparisons for an array of n items in a binary search?

User LPodolski
by
6.3k points

1 Answer

3 votes

Final answer:

The worst possible number of comparisons for an array of n items in a binary search is log2(n) + 1, occurring when the element is not present or is found in the last comparison before exhausting the search space.

Step-by-step explanation:

The worst possible number of comparisons for an array of n items in a binary search occurs when the target element is not present or is at the last middle position checked before the search space is exhausted. In a binary search, the array is divided in half during each step, determining whether the target would be in the left or the right half of the array. This dividing and comparison process continues until the target is found or until there are no more sub-arrays to divide. The worst-case scenario for a binary search is, therefore, log2(n) + 1 comparison, which occurs when the algorithm does one final comparison that results in the search space being reduced to a size of 0 without finding the target. For example, Consider an array with 7 elements, where n = 7. The worst-case number of comparisons would be: The first comparison with n = 7, the Second comparison with n = 3, the Third comparison with n = 1, Fourth comparison (target not found). Each step is a halving of the search space, hence we require at most 3 (which is log2(7) rounded up) plus 1 final comparison, making a total of 4 comparisons.

User Leopal
by
6.9k points