vovuhisback's blog

By vovuhisback, history, 6 years ago, In English

Hello Folks!

I am confused in updating mid value in binary search problems like sometimes (left+right)/2 results in infinite loop & sometimes (left+right+1)/2 results in infinite loop when updated with same left & right.

Any blog post on the same confusion?

  • Vote: I like it
  • +10
  • Vote: I do not like it

| Write comment?
»
6 years ago, hide # |
 
Vote: I like it +33 Vote: I do not like it

This has to do with how you update the left and right values later.

If you do:

if(condition(mid)){
   left=mid;
}
else{
   right=mid-1;
}

Then you need to use mid=(left+right+1)/2.

And if you do:

if(condition(mid)){
   left=mid+1;
}
else{
   right=mid;
}

Then you need to use mid=(left+right)/2.

»
6 years ago, hide # |
 
Vote: I like it +5 Vote: I do not like it
//Binary Search Implementation
while(lo<=hi){
    mid=(lo+hi)/2;
    if(check(mid)) ans=mid, lo=mid+1;
    else hi=mid-1;
}
print ans;





//Binary Search function

int bs(int *arr, int sz, int val) {

	if(arr[sz-1] < val) return sz;
	if(arr[0] >= val) return 0;

	int lo = 0;
	int hi = sz-1;
	int res;
	while(lo <= hi) {
		int mi = (lo + hi) >> 1;

		if(arr[mi] < val) {
			res = mi;
			lo = mi + 1;
		} else {
			hi = mi - 1;
		}
	}

	return res + 1;

}
»
6 years ago, hide # |
 
Vote: I like it +3 Vote: I do not like it

I guess there are different kinds of people, and I will never understand why everyone can't just base their binary searches on maintaining proper invariants.

if (test(L) == false) return /* no solution */;
if (test(R) == true) return R;

while (R - L > 1) {
  int M = (L + R) / 2;
  if (test(M)) {
    L = M;
  } else {
    R = M;
  }
}

return L;

The R - L > 1 condition guarantees that (L + R) / 2 is strictly between L and R (easily proven by contradiction), so the while loop always terminates.

»
6 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Look at Errichto's blog/video here.