Skip to content
GATEiit

GATE DA · Programming, Data Structures and Algorithms

Search algorithms: linear search and binary search

Linear search and binary search: how each works, their best, worst and average comparison counts, tracing lo/mid/hi, first-occurrence variants, and when sorting first pays off.

Before you start

  • Python loops and integer division →

    Binary search code uses `while` loops and `mid = (lo + hi) // 2`.

  • Logarithms

    Binary search cost is ⌊log⁡2n⌋+1 comparisons.

  • Sorting →

    Binary search needs sorted input; the cost of sorting decides whether it is worth it.

This topic comes before: File organization and indexing

Concept notes

1. Linear search

Linear (sequential) search checks the items one by one from the start until it finds the key or runs out.

def linear_search(a, x):
    for i in range(len(a)):
        if a[i] == x:
            return i
    return -1

It works on any list: unsorted, sorted, or a linked list. It needs no extra space.

Case Comparisons
Best (key first) 1
Worst, or key absent n
Average, key present, each position equally likely n+12

The average comes from 1n(1+2+⋯+n)=n+12. If the key is present only with probability p, the expected count is p⋅n+12+(1−p) n.

So linear search is Θ(n) in the worst and average case. It is the right choice for a small list, an unsorted list searched only once or twice, or a structure without random access.

A sentinel variant puts the key at the end of the array so the loop needs no bounds check; the comparison count stays O(n).

2. Binary search

Binary search works on a sorted array with random access. It compares the key with the middle item and throws away the half that cannot contain it.

def binary_search(a, x):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == x:
            return mid
        elif a[mid] < x:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

Invariant: if x is in the array, it lies in a[lo..hi]. Each step at least halves that range, so the loop runs at most ⌊log⁡2n⌋+1 times. Time is O(log⁡n), extra space O(1) (a recursive version uses O(log⁡n) stack).

The details matter in tracing questions:

  • while lo <= hi (not <), otherwise a one-item range is never checked.
  • lo = mid + 1 and hi = mid - 1; writing lo = mid can loop forever.
  • mid uses floor division, so for an even-length range it picks the left middle.

Binary search on a linked list still needs O(n) time, because reaching mid means walking the list.

3. Counting comparisons with a decision tree

Every binary search on n items follows one root-to-node path of a decision tree: the root is the first mid, and each comparison moves left or right.

  • A key found at depth d (root depth 1) costs d comparisons of a[mid] with x.
  • The tree has height ⌊log⁡2n⌋+1, which is the worst case for both successful and unsuccessful search.
  • For n=2k−1 the tree is perfect: depth d holds 2d−1 keys.

Average successful comparisons = (sum of depths of all keys) / n. For n=7: (1⋅1+2⋅2+3⋅4)/7=17/7≈2.43, against (7+1)/2=4 for linear search.

Linear Binary
Needs sorted data No Yes
Needs random access No Yes
Worst case n ⌊log⁡2n⌋+1
Time Θ(n) Θ(log⁡n)

Lower bound: any comparison-based search in a sorted array needs Ω(log⁡n) comparisons in the worst case, since a decision tree with n outcomes has height at least log⁡2n. Binary search is optimal.

Some questions count two comparisons per step (== and <). Read what is being counted.

<><><>a[3]a[1]a[5]a[0]a[2]a[4]a[6]Depth 1: 1 key, depth 2: 2 keys, depth 3: 4 keys. Average success = 17/7
Decision tree of binary search on 7 sorted items

4. Variants and when to sort first

First occurrence of x in a sorted array with duplicates: when a[mid] == x, record mid and continue left (hi = mid - 1). For the last occurrence, continue right. The number of copies of x is last − first + 1, found in O(log⁡n).

Python's bisect module does this: bisect_left(a, x) returns the first index where x could be inserted keeping order (the first occurrence if present), and bisect_right(a, x) returns the index after the last occurrence. So bisect_right(a, x) - bisect_left(a, x) counts copies of x.

Binary search on the answer: if a yes/no condition is false up to some value and true after it (monotonic), binary search finds the boundary. Example: the integer square root of N is the largest m with m2≤N.

Search once or sort first? For k searches in an unsorted array of size n:

  • Linear search every time: Θ(kn).
  • Sort once with an O(nlog⁡n) sort, then binary search: Θ(nlog⁡n+klog⁡n).

Sorting wins once k grows faster than log⁡n. For k=1 linear search is better; for k=Θ(log⁡n) both are Θ(nlog⁡n).

Formulas to remember

Linear search, average successfulEach position equally likely
n+12
Linear search, key present with probability p
p n+12+(1−p) n
Binary search, worst caseComparisons of the key with a[mid]
⌊log⁡2n⌋+1
Middle index
mid=⌊lo+hi2⌋
k searches: sort first vs linear
Θ(nlog⁡n+klog⁡n) vs Θ(kn)

Common mistakes

  • Applying binary search to unsorted data, or claiming O(log⁡n) on a linked list.
  • Writing while lo < hi with hi = mid - 1, which skips the last remaining item.
  • Off-by-one in the worst case: it is ⌊log⁡2n⌋+1, not log⁡2n.
  • Using n/2 for the linear search average; it is (n+1)/2 when the key is present.
  • Forgetting to count both comparisons per step when the question counts == and < separately.

Worked examples

Try each step yourself, then reveal the working.

Example 1: Tracing binary search

numerical

Search for 47 in [3, 8, 15, 21, 30, 38, 47, 52, 66, 71, 89] using the binary search code above. List lo, hi, mid at each step.

  1. Step 1: Start with the full range.

    Try it on paper first.

Example 2: Worst-case comparisons

numerical

A sorted array has 1000 items. What is the largest number of key comparisons binary search can make? How many does linear search need in the worst case?

  1. Step 1: Find the power of 2 around 1000.

    Try it on paper first.

Example 3: Average successful search on 7 items

numerical

Seven distinct keys are stored in a sorted array. Each is searched with equal probability. Find the average number of comparisons for binary search and for linear search.

  1. Step 1: Draw the decision tree.

    Try it on paper first.

Example 4: Finding the first occurrence

numerical

Find the first index of 4 in [2, 4, 4, 4, 4, 7, 9] with the rule: if a[mid] >= x, record mid when equal and set hi = mid - 1; otherwise lo = mid + 1.

  1. Step 1: First step.

    Try it on paper first.

Previous year questions

3 official GATE DA questions on this topic, newest first.

Practise these 3 PYQs →

Topic test

10 questions: up to 3 official PYQs and original practice questions, with GATE marking (MCQ wrong answers lose marks). Score 60% or more to pass. A new set is drawn each time.

Mark as mastered

Loading your progress…

My revision notes

Notes written by the GATEiit team against the official GATE DA syllabus; being checked by a reviewer. Updated 2026-11-21. Spotted a mistake? Use Report an issue on any question, or contact us.