Given n elements, find both the
minimum and maximum
using as few comparisons as possible.
n - 1 comparisons
n - 1 comparisons
Example:
After one comparison per pair:
3, 2, 6, 1
Maximum candidates8, 11, 14, 9
For even n:
n / 2
n / 2 smaller elements:
n / 2 - 1
n / 2 larger elements:
n / 2 - 1
The exact worst-case number of comparisons for arbitrary
n is:
So instead of approximately
2n comparisons,
we need only approximately
1.5n.
Suppose an array begins with zeros and then eventually becomes nonzero:
We want to find the index of the first nonzero, but we do not know where the transition occurs.
Check indices:
Each time the value is still zero, double the index.
Suppose:
Then the first nonzero must lie somewhere between
indices 9 and 16.
Now binary search the interval:
If the middle element is:
0 → move right
If the first nonzero is at position p,
exponential search needs approximately:
probes.
Binary search also needs:
Therefore:
Suppose every row is sorted from left to right and every column is sorted from top to bottom.
| 1 | 4 | 7 | 11 | 15 |
| 2 | 5 | 8 | 12 | 19 |
| 3 | 6 | 9 | 16 | 22 |
| 10 | 13 | 14 | 17 | 24 |
| 18 | 21 | 23 | 26 | 30 |
Let the current value be x.
Why?
Everything below x in the current column
is even larger, so the entire column can be discarded.
Why?
Everything to the left of x in the current
row is even smaller, so the entire row can be discarded.
Search for:
The path is:
For an m × n matrix:
Therefore:
For an m × m matrix:
| Problem | Main Idea | Complexity |
|---|---|---|
| Find min & max | Pair elements first, then run separate min/max tournaments |
⌈3n/2⌉ - 2 comparisons
|
| First nonzero, unknown boundary | Exponential search to find a range, then binary search |
O(log p)
|
| Search sorted matrix | Start top-right and eliminate one row or column at each step |
O(m + n)
|