Here’s how binary search would proceed:
Find the middle element: The array has 10 elements, so the middle index is roughly (0+9)/2=4 (integer division). The element at index 4 is 16.
Compare: Is 23 equal to 16? No. Is 23 greater than 16? Yes.
Narrow the search space: Since 23 is greater than 16 and the array is sorted, we know that if 23 exists in the array, it must be in the right half of the current search space. We can now ignore the left half, including the middle element. Our new search space is:
[23, 38, 56, 72, 91]
Repeat: We repeat the process with our new search space.
- The middle index is now roughly (0+4)/2=2. The element at index 2 is
56. - Is
23equal to56? No. Is23greater than56? No.
Further narrow: Since 23 is smaller than 56, we know it must be in the left half of the current search space. Our new search space is:
[23, 38]
Repeat again:
- The middle index is now (0+1)/2=0. The element at index 0 is
23. - Is
23equal to23? Yes! We have found our element.