Binary search algorithm can be confusing in application.
Normal case: no replicates
Since no replicates, there is only one target we need to find.
1 | int binary_search(int *a, int n, int target) { |
However, in many cases there are replicates in array.
First element
We abstract the array as 00000111111. To find the left edge, that is, the first 1, when we meet one 1, we cannot simply return the index. Rather, we need to shrink right boundary.
1 | // l < r |
If all elements are 0, binary search will return n
, which means there is no desirable value in array.