Searching Algorithms
Linear search checks every element. Binary search cuts the problem in half each step. Learn when to use each, how binary search works exactly, and all its powerful variations.
Quick answer
Linear search checks each element in turn, O(n), and works on any data. Binary search works on sorted data: it compares with the middle element and discards half the range each step, so it is O(log n).
- A billion sorted items take about 30 binary-search steps.
- Compute mid as low + (high - low) / 2 to avoid overflow.
- Binary search on unsorted data gives wrong answers.
#include <stdio.h>
int main(void) {
int a[] = {3, 8, 15, 23, 42, 57, 61, 78, 90};
int target = 61, low = 0, high = 8, step = 0;
while (low <= high) {
int mid = low + (high - low) / 2;
printf("step %d: check a[%d] = %d\n", ++step, mid, a[mid]);
if (a[mid] == target) { printf("found at index %d\n", mid); return 0; }
if (a[mid] < target) low = mid + 1; else high = mid - 1;
}
printf("not found\n");
return 0;
}Output
step 1: check a[4] = 42 step 2: check a[6] = 61 found at index 6
Searching is the act of finding a specific value inside a collection of data. You have already seen linear search in Lesson 3 when we searched arrays. In this lesson we go deeper — understanding exactly when linear search is the right choice, and when binary search makes it hundreds of thousands of times faster.
Binary search is one of the most elegant ideas in all of computer science. A simple trick — always check the middle — that turns a million-item search into just 20 steps. We will understand it completely, implement it two ways, and learn its most useful variations.
Linear Search — Check Every Element
Linear search is the simplest possible search strategy: start from the first element and check each one in order until you either find the target or reach the end. No tricks, no requirements. Works on any array — sorted or unsorted.
Binary Search — The Half-Every-Step Idea
Binary search works on a sorted array only. The insight is simple and powerful: if you check the middle element and it is too big, the target must be in the left half. If it is too small, the target must be in the right half. Either way you eliminate half the remaining elements with every single check.
📖 How you already use binary search every day
When you look up a word in a physical dictionary, you do not start from page 1 and flip through every page. You open somewhere in the middle. If the word you need comes after what you see, you open the right half. If it comes before, you open the left half. You keep halving until you land on the right page. That is binary search — you have been doing it your whole life.
| Array size (n) | Linear search (worst) | Binary search (worst) | How much faster |
|---|---|---|---|
| 100 | 100 | 7 | 14× |
| 1,000 | 1,000 | 10 | 100× |
| 1,000,000 | 1,000,000 | 20 | 50,000× |
| 1,000,000,000 | 1,000,000,000 | 30 | 33,000,000× |
Binary Search — Step by Step Trace
Let us trace binary search on a sorted array to see every decision clearly. We search for target = 23 in [2, 5, 8, 12, 16, 23, 38, 45, 67, 91]
Binary Search — Iterative Version
The iterative version uses a loop with three pointers — low, high, mid. Each iteration either finds the target or narrows the search window by half. This is the version most commonly asked in interviews.
mid = (low + high) / 2 can cause integer overflow when low and high are both large numbers — their sum exceeds the maximum int value. Always write mid = low + (high - low) / 2 instead. This is a well-known bug that existed in Java's standard library for years.Binary Search — Recursive Version
The recursive version expresses the same logic using function calls instead of a loop. The base cases: array is empty (low > high) → not found. Middle element matches → found. Recursive cases: search left half or right half.
Binary Search Variations — The Interview Favourites
Standard binary search finds a position of the target. But interviewers often ask variations. These four come up constantly — learn the subtle changes that make each one work.
Variation 1 — Find First Occurrence of a Repeated Value
In [1, 2, 2, 2, 3, 4], finding 2 could return index 1, 2, or 3. How do you always return the first one (index 1)? When you find the target, do not stop — save the index and keep searching left.
Variation 2 — Find Last Occurrence of a Repeated Value
Same idea, opposite direction. When you find the target, save the index and keep searching right for a later occurrence.
Variation 3 — Count Total Occurrences
Once you have first and last occurrence, count = last - first + 1. O(log n).
Variation 4 — Search in a Rotated Sorted Array
A sorted array has been rotated at some pivot: [4, 5, 6, 7, 0, 1, 2]. Standard binary search breaks here. The fix: one of the two halves is always sorted — check which half is sorted, and use that to decide which half the target could be in.
Bonus — Find Where to Insert (Lower Bound)
A very common interview question: given a sorted array and a target, find the index where target should be inserted to keep the array sorted. If it already exists, return its first position. When the loop ends, low always holds the correct insertion index — because it is the first position where the value is ≥ target.
Decision Guide — Which Search to Use
Common Binary Search Mistakes
You Are Ready for Lesson 9
You now have a complete toolkit for searching — linear search for unsorted data, binary search for sorted data, and four powerful variations for the most common interview scenarios. The overflow-safe midpoint formula and the first/last occurrence patterns alone will save you in dozens of future problems.
In Lesson 9 we build Linked Lists — hierarchical data structures that look like upside-down trees. Trees are everywhere: file systems, HTML pages, databases, compilers. We build binary trees from scratch, learn all four traversal orders, and understand the properties that make trees so powerful.
🎯 Key Takeaways
- ✓Linear search checks every element one by one — O(n) worst case, works on unsorted data
- ✓Binary search requires sorted data — cuts the search space in half every step — O(log n)
- ✓For 1 billion elements: linear search = 1 billion steps, binary search = just 30 steps
- ✓Always use mid = low + (high - low) / 2 — never (low + high) / 2 to avoid integer overflow
- ✓Loop condition is while (low <= high) — the <= matters, not just <
- ✓Always move past mid: low = mid + 1 or high = mid - 1 — never set to mid itself
- ✓First occurrence: when found, save index and search left (high = mid - 1)
- ✓Last occurrence: when found, save index and search right (low = mid + 1)
- ✓Count occurrences = lastOccurrence - firstOccurrence + 1 — still O(log n)
- ✓Rotated array search: identify the sorted half, check if target is in that half, decide direction
Quick check
What does binary search require?
PUT IT INTO PRACTICE
Implement binary search
Use binary search on the sorted input to find the zero-based index of 23 and print 5.
Run or work through the task, then mark it complete when you have checked your result.
HELP US IMPROVE
How was this lesson?
Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.
Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.
