Defitnion

Consider a Boolean function (predicate)

$$ f : {0,1,\dots, n-1} \to {0, 1} $$

which is non‑decreasing:

$$ f(0) \leq f(1) \leq \dots \leq f(n-1) $$

Because the values never switch back from $1$ to $0$, there is at most one $``jump’’$ from $0$ to $1$. Binary search can exploit this property to locate that jump without evaluating $f$ at every index:

  • It seeks the largest index $L$ with $f(L)=0$ and the smallest index $R=L+1$ with $f(R)=1$ (when such indices exist).
  • If the array is all zeros, binary search reports $L=n−1$.
  • If the array is all ones, it reports $L=−1$.

 

Example 1: Lower Bound 12

The example shows a binary search that locates the first element in a sorted vector that is $\geq 12$:

The Code

 

Running

The output should be:

  3
  

 

Code on GitHub

See the implementation code.

 

Example 2: Rightmost 12

The example shows a binary search that returns the index of the last element strictly less than 12 in a sorted vector (yielding $n − 1$ if every element is $<12$ and $‑1$ if none are).

The Code

 

Running

The output should be:

  2
  

 

Code on GitHub

See the implementation code.

 

Example 3: Last 12

The example shows a binary search that returns the index of right‑most element that is $\leq 12$ in a sorted vector.

The Code

 

Running

The output should be:

  5
  

 

Code on GitHub

See the implementation code.

Last updated 11 May 2025, 18:45 +0500 . history