AlgoLab

O(log n)·O(1) space
511181928314243454851515563647377969899

Search runs on a sorted copy of your array, because binary and jump search need sorted input. The bars are that sorted copy.

Searching a sorted array of 20 items for 51 by repeatedly checking the midpoint.

Searching a sorted array of 20 items for 51 by repeatedly checking the midpoint.
  1. 1set the low and high boundaries to the first and last position of the array
  2. 2find the midpoint of the current range
  3. 3compare the value at the midpoint with the target
  4. 4the target is found
  5. 5the target is smaller, so search the left half of the range
  6. 6the target is larger, so search the right half of the range
  7. 7the target is not in the array
Comparisons
0
Writes
0
Accesses
0

Complexity

BestO(1)
AverageO(log n)
WorstO(log n)
Extra spaceO(1)
log₂ n at n=20 predicts 4; this run took 0.

Binary search

Binary search repeatedly checks the midpoint of the remaining range and discards the half that cannot contain the target, halving the search space at every step. It requires the array to be sorted first.

When it is the right choice

Binary search is the right choice whenever the array is already sorted, or will be searched many times, since sorting once and searching repeatedly amortises the cost of the sort. It is the wrong choice for an array that is unsorted and searched only once, where sorting first costs more than a single linear search.

How it works

Worth noticing

Cost

Best
O(1)
Average
O(log n)
Worst
O(log n)
Extra space
O(1)

Worth comparing

All algorithms