awelgorithms

Search a rotated sorted array

Updated

A rotated sorted array is a sorted run that wrapped: [1, 4, 9] became [9, 1, 4] or [4, 9, 1]. One mid still splits the range, but only one side is a sorted run. Identify that run, then drop the half that cannot hold the target.

What to focus on

While L ≤ R: mid = (L+R)//2. If a[mid] equals the target, return mid. If a[L] ≤ a[mid], the left half is sorted — keep it only when the target sits in [a[L], a[mid]). Otherwise keep the right half. Symmetric when the right half is the sorted run.

Worked examples

hit 4

a = [9, 1, 4], target 4
  1. L=0 R=2 mid=1 a[1]=1
  2. 9 ≤ 1 is false so right [1,4] is sorted
  3. 1 < 4 ≤ 4, L=2
  4. mid=2 a[2]=4

Result: index 2

hit 1

a = [4, 9, 1], target 1
  1. L=0 R=2 mid=1 a[1]=9
  2. 4 ≤ 9 so left [4,9] is sorted
  3. 4 ≤ 1 < 9 is false, L=2
  4. mid=2 a[2]=1

Result: index 2

miss 8

a = [9, 1, 4], target 8
  1. L=0 R=2 mid=1 a[1]=1
  2. right sorted, 1 < 8 ≤ 4 is false, R=0
  3. mid=0 a[0]=9 ≠ 8, L=1 > R

Result: not found

Try it

Write search(a, t). a is a rotated sorted array. t is the target. L, mid, and R are indices into a. Sorted on a half means a[L] ≤ … ≤ a[mid] or a[mid] ≤ … ≤ a[R]. Return the index of t, or not found. [9, 1, 4] t=4 → index 2 [9, 1, 4] t=8 → not found [4, 9, 1] t=1 → index 2

a is a non-empty rotated sorted array (one wrap of a non-decreasing run). Target is an integer. L, mid, and R are indices.