Data Structures & Algorithms chapters (13)
  1. 01Introduction to DSA
  2. 02Arrays & Strings Algorithms
  3. 03Searching & Sorting Algorithms
  4. 04Asymptotic Analysis & Complexity
  5. 05Linked Lists
  6. 06Stacks & Queues
  7. 07Hashing & Hash Tables
  8. 08Recursion & Backtracking
  9. 09Binary Trees & BST
  10. 10Heaps & Priority Queues
  11. 11Graphs & Graph Algorithms
  12. 12Greedy Algorithms & Bit Manipulation
  13. 13Dynamic Programming (DP)

Chapter 03

Searching & Sorting Algorithms

4 topics · 2 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

Binary search halves a sorted search space in O(log n); sorting algorithms trade time, space and stability: O(n^2) elementary sorts, O(n log n) merge sort (stable, O(n) space) and quick sort (in-place, O(n^2) worst case).

Sorting/searching is the most tested GATE algorithm topic; lower bound n log n and stability are recurring questions.

Database indexes, lower_bound queries, order statistics, external sorting of large files.

1

Binary Search Algorithm

Binary search finds a target in a sorted array by comparing with the middle element and discarding half each step: T(n)=T(n/2)+O(1)=O(log n). Requires random access and sorted order.

In short: Guess the middle; if too small look right, if too big look left.

Search: find a target value

Think about it

Appears in nearly every interview; the monotone-predicate generalization solves many optimization problems.

Use mid = l + (r - l)//2 to avoid integer overflow in fixed-width languages (l + r can overflow int32).

Loop invariant: if the target exists, it lies in [l, r].

Common bugs: infinite loop from mid=l with l=mid, using < vs <= in loop condition.

Lower bound = first index with a[i] >= x (insertion point); upper bound = first index with a[i] > x.

Count of x = upper - lower.

Search on answer space: if predicate feasible(x) is monotone (False..

False True..

True), binary search the minimum feasible x (capacity to ship packages in D days, Koko eating bananas, aggressive cows).

Rotated sorted array: one half is always sorted; decide which half contains the target.

Floating-point search iterates a fixed number of times instead of testing equality.

Worst case comparisons for n elements: floor(log2 n)+1.

Recursive version uses O(log n) stack; iterative O(1).

Key points

  • Loop invariant: Condition true before each iteration which guarantees correctness.
  • Lower bound: First position where element >= x.
  • Monotone predicate: Once true stays true as x increases; enables answer-space search.
  • Unsorted data: binary search is invalid; linear scan O(n) or sort first.
  • Linked lists do not support O(1) middle access, so binary search is O(n) there.

Example

Code
Three templates:
def binary_search(a, x):
    l, r = 0, len(a) - 1
    while l <= r:
        m = l + (r - l) // 2
        if a[m] == x: return m
        if a[m] < x: l = m + 1
        else: r = m - 1
    return -1

def lower_bound(a, x):           # first i with a[i] >= x
    l, r = 0, len(a)
    while l < r:
        m = (l + r) // 2
        if a[m] < x: l = m + 1
        else: r = m
    return l

def min_capacity(weights, days):  # search on answer
    def ok(cap):
        d, cur = 1, 0
        for w in weights:
            if cur + w > cap: d += 1; cur = 0
            cur += w
        return d <= days
    l, r = max(weights), sum(weights)
    while l < r:
        m = (l + r) // 2
        if ok(m): r = m
        else: l = m + 1
    return l
2

Elementary Sorting Algorithms

Bubble sort repeatedly swaps adjacent out-of-order pairs; selection sort repeatedly selects the minimum of the unsorted part; insertion sort inserts each element into the sorted prefix. All are O(n^2) worst case and in-place (O(1) space).

In short: Simple quadratic sorts that are easy to code and good only for small or almost-sorted data.

Sorting: unordered → ordered

Think about it

GATE regularly asks swaps/comparisons, stability and best-case behaviour of these sorts.

Bubble sort: n(n-1)/2 comparisons worst; with a swapped flag best case O(n) on sorted input; stable; swaps = number of inversions.

Selection sort: always n(n-1)/2 comparisons, at most n-1 swaps (minimum writes, useful when writes are costly); NOT stable in the swap form (e.

g.

[2a,2b,1] swaps 2a past 2b).

Insertion sort: best O(n) on sorted input, worst O(n^2) on reverse-sorted, average O(n^2); stable; adaptive; time = O(n + inversions); online.

Best for tiny n (< ~16-32) and nearly sorted data, so hybrids (Timsort, introsort) switch to insertion sort for small partitions.

Number of inversions in a reverse-sorted array of n: n(n-1)/2 (max).

Shell sort improves insertion sort via gap sequences (about O(n^1.5) or better).

Key points

  • Stable sort: Equal keys keep their original relative order.
  • Inversion: Pair i<j with a[i]>a[j]; insertion sort cost = n + inversions.
  • Adaptive: Runs faster on partially sorted input.
  • Stable: bubble, insertion, merge, counting, radix. Not stable (standard): selection, quick, heap.
  • Comparison sorts have lower bound Omega(n log n): decision tree has n! leaves, height >= log2(n!) = Theta(n log n).

Example

Code
Bubble, selection, insertion:
def bubble(a):
    n = len(a)
    for i in range(n - 1):
        swapped = False
        for j in range(n - 1 - i):
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]; swapped = True
        if not swapped: break

def selection(a):
    n = len(a)
    for i in range(n - 1):
        m = i
        for j in range(i + 1, n):
            if a[j] < a[m]: m = j
        a[i], a[m] = a[m], a[i]

def insertion(a):
    for i in range(1, len(a)):
        key, j = a[i], i - 1
        while j >= 0 and a[j] > key:
            a[j + 1] = a[j]; j -= 1
        a[j + 1] = key
3

Merge Sort Algorithm

Merge sort splits the array in halves, sorts each recursively, and merges two sorted halves in linear time: T(n)=2T(n/2)+Theta(n)=Theta(n log n) in best, average and worst cases. Stable with O(n) auxiliary space for arrays.

In short: Split until single elements, then merge sorted pieces back together.

Merge sort: split → sort → merge

Think about it

The standard stable O(n log n) sort and the template for divide-and-conquer questions (inversions, counting smaller elements).

Merge step: two pointers compare heads and copy the smaller; use <= when taking from the left half to keep stability.

Always Theta(n log n) comparisons (between about (n log n)/2 and n log n - n + 1), recursion depth log n so stack O(log n) plus O(n) buffer.

Not in-place for arrays; for linked lists merge sort is O(1) extra space (excluding stack) and is the preferred sort.

Bottom-up merge sort avoids recursion.

Inversion counting: while merging, when an element from the right half is taken, add the remaining count of the left half; total O(n log n).

Excellent for external sorting (sequential access) and guaranteed worst-case.

Counting-comparison for merging sorted lists of sizes m and n: worst m+n-1.

Key points

  • Merge: Combine two sorted sequences into one in O(m+n).
  • Divide and conquer: Split, solve recursively, combine.

Example

Code
Merge sort with inversion count:
def merge_sort(a):
    if len(a) <= 1: return a, 0
    mid = len(a) // 2
    L, x = merge_sort(a[:mid])
    R, y = merge_sort(a[mid:])
    out, i, j, inv = [], 0, 0, x + y
    while i < len(L) and j < len(R):
        if L[i] <= R[j]:          # <= keeps stability
            out.append(L[i]); i += 1
        else:
            out.append(R[j]); j += 1
            inv += len(L) - i     # inversions across halves
    out += L[i:] + R[j:]
    return out, inv
4

Quick Sort Algorithm

Quick sort picks a pivot, partitions so that smaller elements go left and larger go right, then recursively sorts both sides. Average O(n log n), worst O(n^2) when partitions are maximally unbalanced; in-place with O(log n) average stack; not stable.

In short: Choose a pivot, put smaller things before it and bigger after, repeat on each side.

Quick sort: partition around pivot

Think about it

Most used practical sort; GATE loves its worst-case, partition tracing and quickselect.

Recurrence: T(n)=T(k)+T(n-k-1)+Theta(n).

Best/average: balanced splits give n log n (even a constant 1:9 ratio is still O(n log n)).

Worst: already sorted (or all equal) input with first/last pivot gives T(n)=T(n-1)+n=O(n^2).

Fixes: random pivot (expected O(n log n)), median-of-three, introsort (switch to heap sort when depth > 2 log n).

Lomuto partition: simple, pivot = last, O(n); Hoare partition: fewer swaps, two converging pointers.

Many equal keys need 3-way partition (Dutch flag) to avoid O(n^2).

Recurse on the smaller side and loop on the larger to bound stack at O(log n).

Quickselect finds the k-th smallest in expected O(n) (worst O(n^2); median-of-medians gives worst-case O(n)).

Quick sort beats merge sort in practice for arrays due to cache friendliness and no extra buffer.

Key points

  • Pivot: Element used to split the array.
  • Partition: Rearrange so left <= pivot < right; returns pivot index.
  • Quickselect: Partition-based selection of k-th smallest.

Example

Code
Randomized quick sort and quickselect:
import random

def partition(a, lo, hi):         # Lomuto
    p = random.randint(lo, hi)
    a[p], a[hi] = a[hi], a[p]
    pivot, i = a[hi], lo
    for j in range(lo, hi):
        if a[j] < pivot:
            a[i], a[j] = a[j], a[i]; i += 1
    a[i], a[hi] = a[hi], a[i]
    return i

def quick_sort(a, lo=0, hi=None):
    if hi is None: hi = len(a) - 1
    while lo < hi:
        p = partition(a, lo, hi)
        if p - lo < hi - p:       # recurse on smaller side
            quick_sort(a, lo, p - 1); lo = p + 1
        else:
            quick_sort(a, p + 1, hi); hi = p - 1

def quickselect(a, k):            # k-th smallest, 0-indexed, expected O(n)
    lo, hi = 0, len(a) - 1
    while True:
        p = partition(a, lo, hi)
        if p == k: return a[p]
        if p < k: lo = p + 1
        else: hi = p - 1

Solved examples

Example 01 · Basic

Number of comparisons in binary search worst case for n = 1000?

Given Data:
    Required To Find:

    Comparisons

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: log2(1000) is about 9.97.
    Step 2: floor = 9, plus 1.
    Final Answer: 10 comparisons

    Approach note: Each comparison halves the range: 1000 -> 500 -> ... -> 1 takes ~10 halvings.

    Example 02 · Intermediate

    Count inversions in [3, 1, 2, 5, 4].

    Given Data:
      Required To Find:

      Inversion count

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: (3,1), (3,2), (5,4).
      Step 2: Insertion sort would shift: 1 moves past 3 (1), 2 moves past 3 (1), 4 moves past 5 (1).
      Final Answer: 3

      Approach note: Insertion sort swaps/shifts equal the inversion count.

      Example 03 · Advanced

      Why is quick sort O(n^2) on an array of all equal elements with Lomuto partition, and how to fix it?

      Given Data:
        Required To Find:

        Explanation

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: No element is < pivot, so i never advances and pivot lands at lo.
        Step 2: Left part is empty and right part has n-1 elements, so T(n)=T(n-1)+n=O(n^2).
        Step 3: Use 3-way partition (<, ==, >): equal elements are excluded from both recursive calls, giving O(n) on all-equal input.
        Final Answer: Unbalanced splits; fix with 3-way partitioning or random pivot + equal-key handling

        Approach note: Random pivot alone does not help with all-equal keys.

        Example 04 · Basic

        How many swaps does selection sort perform on [4, 3, 2, 1] (n = 4) in the standard implementation that swaps once per outer pass?

        Given Data:
          Required To Find:

          Swap count

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: One swap per outer iteration (n-1 passes)
          Step 2: n = 4 → 3 swaps
          Step 3: Passes place 1, then 2, then 3
          Final Answer: 3 swaps

          Approach note: Selection sort does O(n) swaps but O(n^2) comparisons.

          Real-world applications

          DSA

          Using Searching & Sorting Algorithms in real projects

          Database indexes, lower_bound queries, order statistics, external sorting of large files.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: Quick sort is always O(n log n).

          Why this is wrong: Bad pivots (sorted input with first/last pivot, all equal keys) give n^2.

          ✅ Verified Truth: Average/expected O(n log n); worst O(n^2). Randomization makes the bad case improbable.

          ⚠️ Exam Tip: GATE: "worst case of quick sort" -> O(n^2).

          ❌ Myth: Selection sort is stable.

          Why this is wrong: The long-distance swap can jump an element over an equal one.

          ✅ Verified Truth: Standard selection sort is unstable; only a shifting variant is stable.

          ⚠️ Exam Tip: Stable list: bubble, insertion, merge, counting, radix.

          ❌ Myth: Binary search works on any array if you are careful.

          Why this is wrong: It relies on order to discard half safely.

          ✅ Verified Truth: Sorted (or monotone predicate) is mandatory.

          ⚠️ Exam Tip: Check the precondition before applying.

          Revision notes

          Binary search halves a sorted search space in O(log n); sorting algorithms trade time, space and stability: O(n^2) elementary sorts, O(n log n) merge sort (stable, O(n) space) and quick sort (in-place, O(n^2) worst case).

          High-Yield Quick Revision Points

          1. Binary search: mid = l + (r-l)//2; lower_bound; search on monotone answer
          2. Insertion O(n)/O(n^2), stable, adaptive; selection <= n-1 swaps, unstable
          3. Merge: Theta(n log n) always, O(n) space, stable; best for linked lists
          4. Quick: avg n log n, worst n^2, in-place, unstable; random pivot; 3-way for duplicates
          5. Comparison sort lower bound: Omega(n log n)

          Practice questions

          Question 1 · MCQ (GATE)

          Best-case time of insertion sort is:

          Question 2 · MCQ (GATE)

          Which sort is NOT stable in its standard form?

          Question 3 · MCQ (GATE)

          Merge sort auxiliary space for arrays:

          Question 4 · MCQ (GATE)

          Quick sort with first-element pivot on sorted input takes:

          Question 5 · MCQ (GATE)

          Minimum number of swaps in selection sort for n elements is at most:

          Question 6 · MCQ (GATE)

          Lower bound for comparison-based sorting: