Knowledge / Computer Science and Engineering / Searching and binary search

Searching and binary search

Computer Science and Engineering (B.E./B.Tech) · Algorithms · free study notes for exams, placements and interviews

In short

Searching means locating a key in a collection, or proving it is absent. Linear search works on any sequence in O(n); binary search exploits order to halve the search space each step and finishes in O(log n) — 30 probes for a billion sorted records instead of a billion. It is examined in every Indian university DAA/Data Structures paper and sits under "Searching, sorting, hashing" in the GATE CSE syllabus (recurrence, comparison counts, decision-tree lower bound). In placements it is the single most reused primitive: TCS NQT, Infosys, Wipro and Capgemini ask the plain version and the off-by-one traps; Amazon, Google, Microsoft, Flipkart, Zoho, Zomato, Swiggy, Walmart Global Tech and PhonePe ask "binary search on the answer" problems almost every round.

Explained

The search problem and linear search

Binary search: idea, invariant and correctness

Writing it without bugs (the part interviews test)

// first index i with a[i] >= k, else n  (lower_bound)
int lower(const vector<int>& a, int k){
    int lo = 0, hi = a.size();              // half-open [lo, hi)
    while (lo < hi){
        int mid = lo + (hi - lo) / 2;
        if (a[mid] < k) lo = mid + 1; else hi = mid;
    }
    return lo;                               // == n means k is larger than all
}
// classic search
int bsearch(const vector<int>& a, int k){
    int lo = 0, hi = (int)a.size() - 1;
    while (lo <= hi){
        int mid = lo + (hi - lo) / 2;
        if (a[mid] == k) return mid;
        if (a[mid] < k) lo = mid + 1; else hi = mid - 1;
    }
    return -1;
}

Complexity, derivation and the lower bound

Variants and relatives

Key points

Formulas and examples

Linear search: worst = n comparisons; average successful = (n + 1)/2; unsuccessful = n
Binary search worst case (3-way) = ⌊log₂ n⌋ + 1 comparisons; iterations (2-way) = ⌈log₂(n + 1)⌉
Recurrence T(n) = T(n/2) + c, T(1) = c ⇒ T(n) = c(log₂ n + 1) = Θ(log n)
Average successful comparisons ≈ log₂ n − 1 (large n, equally likely keys)
Comparison-based lower bound: worst-case comparisons ≥ ⌈log₂(n + 1)⌉
Safe midpoint: mid = lo + (hi − lo)/2 (integer division)
Count of key k = upper_bound(k) − lower_bound(k)
Binary search on an integer answer in [L, R]: iterations = ⌈log₂(R − L + 1)⌉; total time = O(check × log(R − L))
Real-valued bisection: iterations = ⌈log₂((hi − lo)/ε)⌉ for absolute error ε
Jump search: comparisons ≈ n/m + m, minimised at m = √n ⇒ ≈ 2√n
Interpolation search probe: pos = lo + ⌊(k − a[lo]) × (hi − lo) / (a[hi] − a[lo])⌋

(n = number of elements, k = search key, lo/hi = range bounds, ε = tolerance, m = block size; all times in comparisons or probes, which are dimensionless counts.)

Example 1 - trace on 15 sorted marks. a = [12, 18, 23, 29, 35, 41, 47, 52, 58, 63, 70, 77, 84, 91, 98], indices 0-14.

Example 2 - scale of the saving. Comparisons in the worst case:

nLinearBinary ⌈log₂(n+1)⌉
10104
1001007
1,0001,00010
10,00,000 (10⁶)10⁶20
1,00,00,000 (1 crore)10⁷24
100 crore (10⁹)10⁹30

At 10⁸ comparisons/second, scanning 1 crore sorted records takes ≈ 0.1 s; binary search takes 24 comparisons ≈ 0.24 microseconds — about 4 lakh times fewer operations.

Example 3 - duplicates with bounds. a = [2, 4, 4, 4, 7, 9, 9, 11] (indices 0-7), k = 4.

Example 4 - binary search on the answer (allocate minimum pages). Books with pages [12, 34, 67, 90] to be split among 2 students as contiguous blocks; minimise the maximum pages a student reads.

Example 5 - √10 by bisection. lo=0, hi=10, ε = 10⁻³ → iterations needed = ⌈log₂(10/0.001)⌉ = ⌈log₂10000⌉ = ⌈13.29⌉ = 14.

MethodPreconditionAverageWorstSpaceSupports order queries
Linear searchnoneO(n)O(n)O(1)no
Binary searchsorted arrayO(log n)O(log n)O(1)yes (floor/ceil/rank)
Jump searchsorted arrayO(√n)O(√n)O(1)partly
Interpolation searchsorted + uniform keysO(log log n)O(n)O(1)yes
Hash tablehashable keysO(1)O(n)O(n)no
Balanced BST / skip listcomparable keysO(log n)O(log n)O(n)yes, with updates
B+-tree index (disk)sorted indexO(log_B n) I/OO(log_B n) I/OO(n)yes, range scans

Where it is used

Interview questions

Common mistakes

Related topics

Divide and conquer · Time and space complexity · Sorting algorithms · DSA interview patterns · Trees, BSTs and heaps · Hashing and hash tables

Open in the Knowledge reader →Find jobs →