Lesson 4.14: Searching Algorithms
Lesson 4.14: Searching Algorithms
What You'll Learn
- Implement linear search, which checks elements in order and works on data in any order.
- Implement binary search, which requires sorted data and repeatedly halves the search range.
- Explain why binary search depends on sorted input and what happens when that precondition is violated.
- Compare the number of comparisons linear search and binary search make on the same data.
Key Vocabulary
| Term | Definition |
|---|---|
| linear search | Checking each element in order from the start until a match is found or the array ends. |
| binary search | Repeatedly checking the middle of a sorted range and discarding the half that cannot contain the target. |
| precondition | A condition an algorithm assumes is already true before it runs. Binary search's precondition is that the data is sorted. |
| comparison | One check of a target value against an element. The standard way to measure how much work a search does. |
Linear Search
Linear search checks elements one at a time from the front. It makes no assumption about order, which is exactly why it works on any data.
int index = -1;
for (int i = 0; i < data.length && index == -1; i++) {
if (data[i] == target) {
index = i;
}
}
Binary Search
Binary search checks the middle of the current range. If the middle is not the target, the half that CANNOT contain it is discarded entirely.
int low = 0;
int high = data.length - 1;
int index = -1;
while (low <= high && index == -1) {
int mid = (low + high) / 2;
if (data[mid] == target) {
index = mid;
} else if (data[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
⚠️ Binary Search Needs Sorted Data
Every "go left" or "go right" decision assumes the data is in order. Run on unsorted data, that assumption is false, and the result becomes unreliable: a real match can be discarded along with the wrong half.
Comparing the Cost
📌 Halving Beats Scanning, at Scale
Linear search's worst case grows with the length of the array. Binary search's worst case grows with the base-2 logarithm of the length, which is dramatically smaller once the array gets large: a million elements takes roughly 20 comparisons for binary search, not a million.
Practice Questions
Mastery: Searching Algorithms
Get in Touch
Whether you're a student, parent, or teacher — I'd love to hear from you.
Just want free AP CS resources?
Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]