Binary Search vs Linear Search Real Cost Difference in DSA C++ - Complexity Comparison
We want to understand how fast two common search methods work when looking for a number in a list.
Which method finds the number faster as the list grows bigger?
Analyze the time complexity of the following code snippet.
// Linear Search
int linearSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target) return i;
}
return -1;
}
// Binary Search (array must be sorted)
int binarySearch(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
This code shows two ways to find a number: one checks each item one by one, the other splits the list in half repeatedly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation in Linear Search: Checking each element one by one in a loop.
- How many times: Up to n times, where n is the list size.
- Primary operation in Binary Search: Checking the middle element and cutting the search space in half each time.
- How many times: About log₂(n) times, because the list halves each step.
As the list gets bigger, linear search checks more items one by one, while binary search quickly narrows down the search.
| Input Size (n) | Linear Search Checks | Binary Search Checks |
|---|---|---|
| 10 | Up to 10 | About 4 |
| 100 | Up to 100 | About 7 |
| 1000 | Up to 1000 | About 10 |
Pattern observation: Linear search grows directly with list size, binary search grows very slowly as list size grows.
Time Complexity: O(n) for Linear Search, O(log n) for Binary Search
Linear search means checking each item one by one, binary search means cutting the search space in half each step, making it much faster for big lists.
[X] Wrong: "Binary search always works on any list, sorted or not."
[OK] Correct: Binary search only works correctly if the list is sorted; otherwise, it can miss the target or give wrong results.
Knowing when to use linear or binary search shows you understand how to pick the right tool for the job, a key skill in coding and problem solving.
"What if the list is not sorted but we still want faster search than linear? How would the time complexity change if we used a different data structure like a hash table?"