Algorithm Search⌘K

Problemintro

Search in a sorted array

Also called sorted search, ordered search.

Given a sorted array and a key, find an index of the key, or report that the key is not in the array.

Time
Ω(log n) worst
Where
n = the number of items

In plain words

You have a list of items in order, such as the words in a dictionary. You want to know if a word is in the list, and where. Because the list is in order, you do not need to look at each item.

Definition

Input. An array A[0…n−1]A[0 \ldots n-1] with A[0]≤A[1]≤⋯≤A[n−1]A[0] \le A[1] \le \cdots \le A[n-1] under a total order, and a key xx.

Output. An index ii with A[i]=xA[i] = x, or NIL when no such index exists.

Variants

  • Lower bound. Find the smallest index ii with A[i]≥xA[i] \ge x. This is also the number of items less than xx.
  • Upper bound. Find the smallest index ii with A[i]>xA[i] > x.
  • Predecessor and successor. Find the largest item less than xx, or the smallest item larger than xx.
  • Unknown length. The array is very long, or its length is not known.

Examples

A x output
2 5 8 12 16 23 38 23 5
2 5 8 12 16 23 38 7 NIL
1 3 3 3 5 3 1, 2 or 3

Known algorithms

AlgorithmTimeSpacePropertiesCode
Binary searchΘ(log n) worst · averageΘ(1) extracomparison baseddeterministiciterative10 languages

Bounds

In the comparison model with three-way comparisons, each algorithm needs ⌈lg⁡(n+1)⌉\lceil \lg(n+1) \rceil comparisons in the worst case. A decision tree for the problem must have a different outcome for each of the nn positions and for "not found". Binary search reaches this bound. If the algorithm can do arithmetic on the keys, interpolation search uses O(log⁡log⁡n)O(\log \log n) steps on average for keys from a uniform distribution.

Applications

  • Look up a key in a sorted table, such as a symbol table or an index on disk.
  • Count the items in a range [x,y][x, y] with two lower-bound searches.
  • Search on the answer: find the smallest value that satisfies a monotone test.

References

  1. Donald E. Knuth, The Art of Computer Programming, Volume 3, second edition, Section 6.2.1

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proof
  • add a proof in proofs/ (06.5)
Lean
  • name a Lean module in the lean field (07)
Visual
  • add viz/scene.ts or a figure (10)
Writing
  • the lead paragraph