Binary Search is an algorithm that counts the number of true values in a sequence of booleans satisfying in time and space.

Algorithm

Consider solving the problem after the number of true values has been determined to satisfy .

Let .

  • If is true, must all be true, which implies . Solve for the problem with and recursively.
  • Otherwise, must all be false, which implies . Solve for the problem with and recursively.

This algorithm solves the problem in time and space.

int binary_search(int n, const std::vector<bool> &f) {
	if (!f[0]) {
		return 0;
	}
 
	int l = 0, r = n;
	while (l + 1 < r) {
		int mid = std::midpoint(l, r);
		if (f[mid]) {
			l = mid;
		} else {
			r = mid;
		}
	}
	return r;
}