awelgorithms

Peak finding with binary search

Updated

A peak index i satisfies a[i] ≥ neighbors (ends have one neighbor). On an array that rises then falls, or that is strictly bitonic, compare a[mid] with a[mid+1]: go right while the slope is up, else shrink right to mid.

What to focus on

The remaining range always still contains a peak. Stop when L==R; that index is a peak. For a = [1, 4, 9, 1] the peak is index 2.

Worked examples

interior peak

a = [1, 4, 9, 1]
  1. L=0 R=3 mid=1, a[1]=4 < a[2]=9, L=2
  2. L=2 R=3 mid=2, a[2]=9 > a[3]=1, R=2
  3. L==R

Result: peak index 2

rising to the end

a = [1, 4, 9]
  1. L=0 R=2 mid=1, 4 < 9, L=2
  2. L==R=2

Result: peak index 2

falling from the start

a = [9, 4, 1]
  1. L=0 R=2 mid=1, 4 > 1, R=1
  2. L=0 R=1 mid=0, 9 > 4, R=0
  3. L==R

Result: peak index 0

Try it

Write peak(a). a is the array. L, mid, and R are indices. Compare a[mid] with a[mid+1] to decide which side still holds a peak. Return the peak index. Stop when L==R. [1, 4, 9, 1] → peak index 2 [1, 4, 9] → peak index 2 [9, 4, 1] → peak index 0

a is a non-empty integer array, length ≥ 2 so mid+1 is defined until L==R. A peak exists. L, mid, and R are indices.