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
- Model
- Comparison model
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 with under a total order, and a key .
Output. An index with , or NIL when no such index exists.
Variants
- Lower bound. Find the smallest index with . This is also the number of items less than .
- Upper bound. Find the smallest index with .
- Predecessor and successor. Find the largest item less than , or the smallest item larger than .
- 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
| Algorithm | Time | Space | Properties | Code |
|---|---|---|---|---|
| Binary search | Θ(log n) worst · average | Θ(1) extra | comparison baseddeterministiciterative | 10 languages |
Bounds
In the comparison model with three-way comparisons, each algorithm needs comparisons in the worst case. A decision tree for the problem must have a different outcome for each of the positions and for "not found". Binary search reaches this bound. If the algorithm can do arithmetic on the keys, interpolation search uses 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 with two lower-bound searches.
- Search on the answer: find the smallest value that satisfies a monotone test.
References
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof |
| |
| Lean |
| |
| Visual |
| |
| Writing |
|
Tag 6SRCHA Edit this page History Report an error Markdown JSON