Binary search is a very familiar algorithm to most people here. A typical implementation looks like this:

```
// x = array of numbers
// n = length of the array
// k = search key
// returns "true" if the key is found, "false" otherwise
bool search(int x[], int n, int k) {
int l = 0, r = n-1;
while (l <= r) {
int m = (l+r)/2;
if (x[m] == k) return true;
if (x[m] < k) l = m+1; else r = m-1;
}
return false;
}
```

However, even if the idea is straightforward, there are often bugs in binary search implementations. How exactly to update the search bounds and what is the condition when the search should stop?

Here is an alternative binary search implementation that is shorter and should be easier to get correct:

```
bool search(int x[], int n, int k) {
int p = 0;
for (int a = n; a >= 1; a /= 2) {
while (p+a < n && x[p+a] <= k) p += a;
}
return x[p] == k;
}
```

The idea is to implement binary search like linear search but with larger steps. Variable p contains the current array index, and variable a contains the step length. During the search, the step length is n, n/2, n/4, ..., 1. Finally, p contains the largest index whose value is not larger than the search key.

A similar idea can be applied to binary search variations. For example, the following code counts how many times the key appears in the array. After the search, [p+1..q] is the range with value k.

```
int count(int x[], int n, int k) {
int p = -1, q = -1;
for (int a = n; a >= 1; a /= 2) {
while (p+a < n && x[p+a] < k) p += a;
while (q+a < n && x[q+a] <= k) q += a;
}
return q-p;
}
```

Do you know other tips how to implement binary search correctly?

thanks for the second implementation it was a new and of course tricky implementation to me.:D

Well, imagine you an array [0..

n- 1] and let us have an invariant: some functionFwhich returnsTruefor everya[i] as an argument for anyifrom [0..k] andFalsefor everya[j] forjfrom [k+ 1..n- 1]. Then my binary search which actually finds the border between these two parts of the array looks the following way:You can easily prove that

l=kandr=k+ 1 by the end of the while loop. In this case no worries about whether to increasemby 1 or not.As an example this is the code which determines whether an element

xexists in the sorted array [0..n-1]:http://codeforces.com/contest/812/problem/C I got many bugs earlier , but with your implementation , AC in one go :)

BTW , do you always use this implementation , or adapt different version like h = mid + 1 etc , sometimes?

As a suggestion, As we all know that Binary Search runs in O(logn) so implementing it recursive will not only be that bad in case of running time or memory, but also it can decrease the number of bugs you might have :)

And one other bug that anyone could have is stop condition of binary search. As a suggestion you can have a condition that when r-l<=2 check remaining items yourself. It can also decrease the number of bugs you might have.

And as the final word, bounds are very important in implementing binary search. Searching for the first occurrence, last one, or the one after last one,or etc. will require different bounds of passing middle point and left or right to the function.

Here is an example usage of Binary Search for Problem C,Round 218 : 5384392

P.S. Sorry for my bad english :)

Usually, when I have doubts about errors implementing binary search, which are common when I have to find things like "the largest element with this and that conditions..." (also lower_bound, upper_bound, etc), I do the following. I make the main loop of the binary search like this:

while (hi-lo > 5) { // here the usual binary search code }

and then, after that, a small linear loop for getting the correct result.

while (lo != hi) // increment or decrement hi or lo, respectively

The number 5 has nothing of special. It only ensures that the remaining interval is small enough. This avoids the possibility of errors on termination of the main loop of binary search, or the wrong choose of lo or hi. Although this approach is nice for saving you during a contest, it is not that good for understanding and proving correctness, which is fair more valuable IMHO.

I hope it was useful.

Let me try to generalize novaco's answer a bit:

So far, every single time I used (integer) binary search, I could formulate the problem in one of two ways:

(1) Given a range of integers

R= {l,l+ 1, ...,r- 1,r} and amonotonically increasingpredicateP, find the smallest for whichP(x) holds true. I then use the following code:This might not work if

P(r) = 0 (in this case the algorithm will returnx=r), but you can easily extend your search range to`r + 1`

and artificially setP(r+ 1) = 1 or you can just precheck for that situation.(2) Given a range of integers

R= {l,l+ 1, ...,r- 1,r} and amonotonically decreasingpredicateP, find the largest for whichP(x) holds true. If we setQ(x) = !P(x), thenQis increasing and we can use (1) to findx+ 1. We can also just use the following slightly modified variant:I find this approach so intuitive that I haven't done a single mistake while implementing binary search since.

In the case of finding the occurence of an element

kin a sorted array, I would use variant (1) to find the first element`i >= k`

and then check whether`i = k`

. Note that in the case wherek>x[n- 1] the algorithm still works because of the equality check at the end.So, to summarize, you don't need to use this particular method, but you should have realized that there is really

only onetype of problem that can be solved with binary search and stick toonly oneparticular implementation to solve this problem. You won't make a single mistake with binary search from there on.i found a good binary search problem. and in my experience when you wanna minimize the maximum of something or maximize the minimum of something binary search is a good idea.

I lost track of how many problems I couldn't solve because of bad binary search implementations. Even this year during IOI I couldn't manage to solve completely one of the problems because my binary search had a bug that I wasn't able to find :(

if an array contains the following data: 1 2 3 4 4 4 4 4 4 6 7 8 Now I want to find the position of first occurance of data 4. How can I implement binary search for this problem? Here, the answer should be 3.

Something like this:

This guarantees that you won't miss the earliest occurrence of 4, since whenever you see a 4, it's the right bound that is modified, not the left bound.

Generalized implementation of

lower boundfor non-decreasing func :Actually you don't need

`while`

in your second implementation. You can use just`if`

, can't you?while is needed, because the steps are not always powers of 2.

I used to write binary search like this:

I think this is more like Exponential search. It always performs at least as efficient as binary search.