Search code examples
algorithmbinary-search

How many comparisons needed in binary search of this array?


We have the following array: [4, 13, 25, 33, 38, 41, 55, 71, 73, 84, 86, 92, 97] To me it seems like there are only 3 comparisons needed to find 25, because: First we pick the middle element 55. Now we perform two comparisons: 55 = 25? 55 > 25? None of these hold so we go to the left of the array. We get the subarray: [4, 13, 25, 33, 38, 41] We divide this again and get 25 = 25? yes.. So it took 3 comparisons to get our match. My book says there are four comparisons needed to find 25. Why is this?


Solution

  • As the size of the left array is even, each algorithm could select one of the middle numbers. Hence, the comparison could be like the following with 4 comparison:

    [4, 13, 25, 33, 38, 41, 55, 71, 73, 84, 86, 92, 97]
    25 < 55 =>‌ [4, 13, 25, 33, 38, 41]
    25 < 33 => [4, 13, 25]
    25 > 13 => [25]
    25 == 25 => Found.