Search in rotated sorted array
Intermediate · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A rotated sorted array is a sorted list that was cut at some point and had its two parts swapped, like 6 7 8 1 2 3 4 5. You can still search it quickly, because at every step at least one half is perfectly in order.
Practical use cases
- Web app: Wrap-around log buffer. An app keeps its last 1,000 log lines in a circular buffer, where new lines overwrite the oldest. The timestamps are in order but start in the middle of the array. Searching for a time uses this idea, without re-arranging the buffer first.
- Web app: Daily schedule that wraps past midnight. A shift roster lists hours in sorted order that wraps around midnight, for example 22:00, 23:00, 01:00, 06:00. Finding a given hour needs to handle that wrap. The code only has to work out which half is in proper order, so it never has to unwrap the list and lookups stay quick.
- System: Circular buffers in networking. Network cards and audio apps store data in fixed circular buffers, so the oldest item can sit anywhere. Searching them without copying is a real need, and this approach searches the data exactly where it sits, in a few steps.
The story: The Spun Bookshelf
The school library had books numbered in order, 5, 10, 20, 30, 40, 50, 60. But during Diwali cleaning someone took the last three books and put them in front. The shelf now read: 40, 50, 60, 5, 10, 20, 30. It is still two sorted runs, but with a cliff in the middle where 60 drops to 5.
Mira needed book 10. Normal binary search would be confused: the middle book is 5. "Is 10 bigger? Yes, go right." That happens to work here, but with another target like 50 it would send her the wrong way. The cliff breaks the simple rule.
Then she noticed something lovely: whenever you cut the shelf at the middle, at least one half is perfectly sorted. Check the left end against the middle: if the left end is smaller, the left half has no cliff. Is your book inside that sorted half? Then go there. If not, the other half it is. One more check, one half discarded, and the search is logarithmic again.
How to spot this problem, and where you need it
Data that was once sorted has been shifted around a pivot, so a normal binary search fails, but you still want a fast search without sorting again.
Signs you need it
- The problem says "rotated sorted array", "pivot" or "sorted but shifted".
- The list looks sorted except for one sudden drop where it wraps from a large value to a small one.
- Plain binary search gives wrong answers on your circular buffer or wrap-around schedule, because the middle comparison misleads you.
Where to use it in a project
- Searching ring buffers that hold recent logs, events, or metrics in time order.
- Schedules and timetables that wrap around midnight or around the end of a week.
The solution
Look at the middle item. Compare it with the leftmost item to find which half is properly sorted. If your target lies inside the sorted half, search there. Otherwise search the other half. Repeat. Each step still throws away half the list, because one half is always safe to reason about, so you never need to find the pivot or re-sort.
Payoff: Before: scanning all 1,000 or 1 lakh entries. After: about 10 to 17 checks, even though the data is shifted.
Explain it like I am 8
Imagine a circle of numbered stools that someone spun, so the starting number is somewhere in the middle. You stand at a stool and look at a half: one of the halves is still counting up properly. Is your number in that half? If yes, go there. If not, go to the other half.
How it works, step by step
- Compute mid as usual. If
a[mid]is the target, you are done. - Find which half is sorted: if
a[low] <= a[mid]the left half is sorted. Otherwise the right half is. - If the left half is sorted and the target lies in
[a[low], a[mid]), search the left (high = mid - 1). Else search the right. - If the right half is sorted and the target lies in
(a[mid], a[high]], search the right (low = mid + 1). Else search the left. - Repeat until found or low passes high (return -1).
The code in four languages
PHP
<?php
// Search $target in a sorted array that was rotated (no duplicates). Returns index or -1.
function searchRotated(array $a, int $target): int {
$low = 0;
$high = count($a) - 1;
while ($low <= $high) {
$mid = intdiv($low + $high, 2);
if ($a[$mid] === $target) return $mid;
if ($a[$low] <= $a[$mid]) { // left half is sorted
if ($a[$low] <= $target && $target < $a[$mid]) {
$high = $mid - 1; // target is inside the sorted left half
} else {
$low = $mid + 1;
}
} else { // right half is sorted
if ($a[$mid] < $target && $target <= $a[$high]) {
$low = $mid + 1; // target is inside the sorted right half
} else {
$high = $mid - 1;
}
}
}
return -1;
}
$shelf = [40, 50, 60, 5, 10, 20, 30];
echo searchRotated($shelf, 10), "\n"; // 4
echo searchRotated($shelf, 50), "\n"; // 1
echo searchRotated($shelf, 7), "\n"; // -1JavaScript
// Search target in a sorted array that was rotated (no duplicates). Returns index or -1.
function searchRotated(a, target) {
let low = 0;
let high = a.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (a[mid] === target) return mid;
if (a[low] <= a[mid]) { // left half is sorted
if (a[low] <= target && target < a[mid]) {
high = mid - 1; // target is inside the sorted left half
} else {
low = mid + 1;
}
} else { // right half is sorted
if (a[mid] < target && target <= a[high]) {
low = mid + 1; // target is inside the sorted right half
} else {
high = mid - 1;
}
}
}
return -1;
}
const shelf = [40, 50, 60, 5, 10, 20, 30];
console.log(searchRotated(shelf, 10)); // 4
console.log(searchRotated(shelf, 50)); // 1
console.log(searchRotated(shelf, 7)); // -1Java
public class Main {
// Search target in a sorted array that was rotated (no duplicates). Returns index or -1.
static int searchRotated(int[] a, int target) {
int low = 0;
int high = a.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] == target) return mid;
if (a[low] <= a[mid]) { // left half is sorted
if (a[low] <= target && target < a[mid]) {
high = mid - 1; // target is inside the sorted left half
} else {
low = mid + 1;
}
} else { // right half is sorted
if (a[mid] < target && target <= a[high]) {
low = mid + 1; // target is inside the sorted right half
} else {
high = mid - 1;
}
}
}
return -1;
}
public static void main(String[] args) {
int[] shelf = {40, 50, 60, 5, 10, 20, 30};
System.out.println(searchRotated(shelf, 10)); // 4
System.out.println(searchRotated(shelf, 50)); // 1
System.out.println(searchRotated(shelf, 7)); // -1
}
}Go
package main
import "fmt"
// searchRotated searches target in a sorted slice that was rotated (no duplicates). Returns index or -1.
func searchRotated(a []int, target int) int {
low := 0
high := len(a) - 1
for low <= high {
mid := low + (high-low)/2
if a[mid] == target {
return mid
}
if a[low] <= a[mid] { // left half is sorted
if a[low] <= target && target < a[mid] {
high = mid - 1 // target is inside the sorted left half
} else {
low = mid + 1
}
} else { // right half is sorted
if a[mid] < target && target <= a[high] {
low = mid + 1 // target is inside the sorted right half
} else {
high = mid - 1
}
}
}
return -1
}
func main() {
shelf := []int{40, 50, 60, 5, 10, 20, 30}
fmt.Println(searchRotated(shelf, 10)) // 4
fmt.Println(searchRotated(shelf, 50)) // 1
fmt.Println(searchRotated(shelf, 7)) // -1
}Time: O(log n) · Extra space: O(1). Each step still throws away half the shelf. (With many duplicates the worst case can slip toward O(n).)
Watch out for
- Using the plain rule "target > mid goes right" which breaks at the cliff.
- Writing
a[low] < a[mid]instead of<=; when low equals mid (two items left) the left half is still "sorted". - Forgetting the target could equal the boundary item; one side of the range check must be inclusive.
Quick check
- Why does the trick work?
- At least one half around the middle is always sorted
- Rotation sorts the list again
- The cliff is always at the middle
- a[low] <= a[mid] tells you that...
- The right half is sorted
- The target is at mid
- The left half is sorted
- Time complexity (no duplicates)?
- O(n)
- O(n log n)
- O(log n)