DEV Community

Ankit Maheshwari
Ankit Maheshwari

Posted on • Originally published at bitveen.com

Linear Search vs Binary Search — Differences, Code & Complexity

The difference between linear and binary search is the difference between O(n) and O(log n) — which at scale means millions of operations vs 20.

🔍 Linear Search

function linearSearch(arr, target) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === target) return i;
  }
  return -1;
}
Enter fullscreen mode Exit fullscreen mode
  • Time: O(n) | Space: O(1) | Works on: unsorted ✅

🔍 Binary Search

function binarySearch(arr, target) {
  let left = 0, right = arr.length - 1;
  while (left <= right) {
    const mid = Math.floor((left + right) / 2);
    if (arr[mid] === target) return mid;
    else if (arr[mid] < target) left = mid + 1;
    else right = mid - 1;
  }
  return -1;
}
Enter fullscreen mode Exit fullscreen mode
  • Time: O(log n) | Space: O(1) | Requires: sorted array ⚠️

Why O(log n)? With 1,000,000 elements → at most 20 steps.

⚖️ Comparison

Factor Linear Binary
Requires sorted ❌ No ✅ Yes
Time complexity O(n) O(log n)
Space complexity O(1) O(1)
Best for Small/unsorted Large sorted data

⚠️ Critical Rule

Binary search on unsorted data gives wrong results with no error. Always sort first.

🎯 Interview Q&A

Q: Binary search on linked list?
A: O(n) to find mid makes it pointless. Use arrays.

Q: Find first occurrence in duplicates?
A: Modified binary search — continue left even after finding a match.


Part 6 of the Bitveen DSA Series. Originally published at bitveen.com

Top comments (0)