Lesson 11 of 19
Binary search
A sorted shelf lets you skip whole sections. Compare the middle book with your target, then keep the half where the target could still be.
Keep a range that could still contain the answer
On an ascending array, every value left of the middle is at most the middle value. This lets one comparison rule out a whole group. Keep two indexes for the remaining range. After a miss, move past the middle you just checked so the range always shrinks.
Work through an example
Look for 9 in [2, 4, 8, 12, 16]. Which values do you inspect, and how do you know when to stop?
Step-by-step solution
- Start with indexes 0 through 4. The middle value is 8. Since 9 is larger, keep indexes 3 through 4.
- Choose the left middle of those two positions. Its value is 12. Since 9 is smaller, the upper bound moves to index 2.
- The lower bound is 3 and the upper bound is 2. The range is empty, so 9 is absent after two comparisons.
JavaScript example
function locate(sorted, target) {
let low = 0, high = sorted.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (sorted[mid] === target) return mid;
if (sorted[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
locate([2, 4, 8, 12, 16], 9); // -1 means absentDSA compiler
Try it yourself
Finish the animation to unlock this question.
The middle value is 12. On an ascending shelf, where can 9 still be?
Related exercise · Binary search · See this stage of the beginner path