Binary Search — Thinking by Comparing with the Answer

Words: 183

Binary search is not so much an algorithm as a way of thinking.

Core code

cpp
1
2
3
4
5
6
7
	while(l<=r) {
		mid=(l+r)/2;
		if(judge(mid)) {
			r=mid-1;
		} else
			l=mid+1;
	}

Advantages

It brings an ordinary search down from O(n) to O(log n).

Requirements

The data you search must be sorted.

Explanation

Binary search shrinks the range in which the answer can lie, again and again, until the optimum is found. In coursework and in contests you will often meet problems that combine binary thinking with some other algorithm.

Uses

Finding a value in a sorted array

Binary search can answer, for a given array,

  1. whether a value exists
  2. where that value sits

Solving an equation within a tolerance

Halve the interval over and over until the solution is precise enough.

Maximising the minimum

Minimising the average

Problems of this shape are easy to compare because you can tell whether a candidate is above or below the real answer. So even without knowing what the answer is, you can shrink its range by comparison.

Reference:
Programming Contest Challenge Book
Baidu Baike

Loading...