Bitonic array search
Updated
A bitonic array increases then decreases. Search is: find the peak with binary search, then binary search the ascending prefix, then the descending suffix (or stop at the first hit).
What to focus on
Ascending side: ordinary a[mid] vs target. Descending side: if a[mid] < target the larger values sit to the left, so R=mid-1. Peak a = [1, 4, 9, 1] is index 2.
Worked examples
hit on the rise
a = [1, 4, 9, 1], target 4- peak at 2
- binary search [0, 2]: L=0 R=2 mid=1 a[1]=4
Result: index 1
hit on the fall
a = [2, 4, 9, 1], target 1- peak at 2
- ascending [0,2] misses 1
- descending [2,3]: L=2 R=3 mid=2 a[2]=9 > 1, L=3 a[3]=1
Result: index 3
only on the fall
a = [1, 4, 9, 6, 2], target 6- peak at 2 (value 9)
- ascending [0,2] misses 6
- descending [2,4]: L=2 R=4 mid=3 a[3]=6
Result: index 3
Try it
Write bitonicSearch(a, t). a is a bitonic array (strictly up, then strictly down). t is the target. L, mid, and R are indices on the peak search, then on each half. Return the index of t. [1, 4, 9, 1] t=4 → index 1 [2, 4, 9, 1] t=1 → index 3 [1, 4, 9, 6, 2] t=6 → index 3
a is non-empty bitonic: strictly increases then strictly decreases. The target exists. L, mid, and R are indices.