How do computers find a needle in a haystack? Does sorting the haystack help?
In a standard (unsorted) list, you must check every single number one by one until you find a match. This is called Linear Search.
Yes, immensely. If the list is sorted, you can eliminate half the remaining numbers with every single guess. This is called Binary Search.
Imagine a shuffled deck of cards. To find the Queen of Hearts, you have to turn over the top card, check it, then the next, and so on. You might find it instantly (Best Case), or it might be the very last card (Worst Case).
Now imagine a phone book (which is sorted alphabetically). To find "Smith", you open the book to the middle. If you see "M", you know "S" is in the second half. You ignore the entire first half. You repeat this split until you find the name.
Note: Graph is illustrative. Logarithmic growth is significantly flatter than linear.
| Algorithm | Big O (Time) | Input Requirement |
|---|---|---|
| Linear Search | O(n) | None (Any Array) |
| Binary Search | O(log n) | Must be Sorted |
If you have 1,000,000 items:
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
guess = arr[mid]
if guess == target:
return mid
if guess > target:
high = mid - 1
else:
low = mid + 1
return -1 # Not found
function binarySearch(arr, target) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
let mid = Math.floor((low + high) / 2);
let guess = arr[mid];
if (guess === target) return mid;
if (guess > target) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1; // Not found
}