Skip to content
Chethan Yadav_
Data Structures & Algorithms

DSA/Lesson 9 of 11/7 min read

Sorting and Searching

Comparison and non-comparison sorts, stability, merge sort, quick sort, counting and radix sort, binary search and its variants.


On this page

Sorting Algorithm overview

AlgorithmBestAverageWorstSpaceStable
BubbleO(n)O(n^2)O(n^2)O(1)Yes
SelectionO(n^2)O(n^2)O(n^2)O(1)No
InsertionO(n)O(n^2)O(n^2)O(1)Yes
MergeO(n log n)O(n log n)O(n log n)O(n)Yes
QuickO(n log n)O(n log n)O(n^2)O(log n)No
HeapO(n log n)O(n log n)O(n log n)O(1)No
CountingO(n + k)O(n + k)O(n + k)O(k)Yes
RadixO(d(n + b))O(d(n + b))O(d(n + b))O(n + b)Yes

Any comparison-based sort needs Omega(n log n) comparisons in the worst case: a decision tree must have n! leaves, so its height is at least log(n!) = Theta(n log n).

Stable Sort

A sort is stable if equal elements keep their original relative order. It matters when sorting by multiple keys: sort by name, then stable sort by age, and people of the same age stay sorted by name.

Python sorted (Timsort) and Java Arrays.sort for objects are stable. Java Arrays.sort for primitives uses dual-pivot quicksort, which is not.

Simple quadratic sorts

Bubble Sort

Repeatedly swap adjacent out-of-order pairs. After pass i, the largest i elements are in place. Stop early if a pass makes no swaps (best case O(n)).

Selection Sort

Find the minimum of the unsorted part and swap it to the front. Always O(n^2) comparisons but only O(n) swaps, useful when writes are expensive.

Insertion Sort

Grow a sorted prefix by inserting each new element into place.

def insertion_sort(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

Fast on small or nearly sorted arrays, which is why Timsort and introsort use it for small runs.

Merge Sort

Divide and conquer: split in half, sort each half, merge.

def merge_sort(a):
    if len(a) <= 1:
        return a
    mid = len(a) // 2
    left, right = merge_sort(a[:mid]), merge_sort(a[mid:])
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:   # <= keeps it stable
            out.append(left[i]); i += 1
        else:
            out.append(right[j]); j += 1
    return out + left[i:] + right[j:]

T(n) = 2T(n/2) + O(n) = O(n log n) always. Needs O(n) extra space. Preferred for linked lists (no random access needed) and for external sorting of data larger than memory.

Bonus: counting inversions is a merge sort with a counter in the merge step.

Quick Sort

Pick a pivot, partition so smaller elements go left and larger go right, recurse on both sides.

def quick_sort(a, lo, hi):
    if lo >= hi:
        return
    pivot, i = a[hi], lo
    for j in range(lo, hi):          # Lomuto partition
        if a[j] < pivot:
            a[i], a[j] = a[j], a[i]
            i += 1
    a[i], a[hi] = a[hi], a[i]
    quick_sort(a, lo, i - 1)
    quick_sort(a, i + 1, hi)
  • Average O(n log n), in place, very cache friendly, usually the fastest in practice.
  • Worst case O(n^2) when the pivot is always the min or max (for example, sorted input with last-element pivot).
  • Fixes: random pivot, median-of-three, and three-way partitioning for many duplicates.
Merge sortQuick sort
Worst caseO(n log n)O(n^2)
Extra spaceO(n)O(log n) stack
StableYesNo
Cache behaviorGoodBetter

Quickselect

Find the k-th smallest element by partitioning and recursing into only one side. Average O(n), worst O(n^2); median of medians guarantees O(n).

Non-comparison sorts

Counting Sort

For integers in a small range [0, k]: count occurrences, compute prefix sums for positions, then place elements (iterate backwards to stay stable). O(n + k).

Radix Sort

Sort by each digit from least significant to most, using a stable counting sort per digit. O(d * (n + b)) for d digits in base b. Good for fixed-width integers and strings.

Bucket sort: scatter uniformly distributed floats into n buckets, sort each, concatenate. O(n) average.

Search a sorted (or monotonic) space by halving it each step. O(log n).

def binary_search(a, target):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = lo + (hi - lo) // 2   # avoids overflow in fixed-width ints
        if a[mid] == target:
            return mid
        if a[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

Lower bound and upper bound

  • Lower bound: first index with a[i] >= x.
  • Upper bound: first index with a[i] > x.

Count of x = upper bound minus lower bound. Python has bisect_left and bisect_right.

Common variants

ProblemTrick
Search in rotated sorted arrayOne half is always sorted; check if the target is in it
Find minimum in rotated arrayCompare a[mid] with a[hi]
Peak elementMove toward the larger neighbor
First and last positionLower and upper bound
Search a 2D sorted matrixTreat as a flat array of m * n
Median of two sorted arraysBinary search the partition, O(log min(m, n))

Binary Search on Answer

When the answer is a number and feasibility is monotonic (if x works, every larger x works), binary search over the answer and test each candidate with a greedy check.

Examples: Koko eating bananas, ship packages within D days, split array largest sum, aggressive cows, minimum time to finish jobs.

lo, hi = min_possible, max_possible
while lo < hi:
    mid = (lo + hi) // 2
    if feasible(mid):
        hi = mid
    else:
        lo = mid + 1
return lo

Pitfalls: infinite loops from lo = mid with mid = (lo + hi) // 2; use (lo + hi + 1) // 2 when moving lo = mid. Decide upfront whether the interval is closed or half-open, and stick to it.

Quick revision

  • Comparison sorts are Omega(n log n); counting and radix sort beat it for bounded integers.
  • Stable: insertion, merge, counting, radix, Timsort. Not stable: selection, quick, heap.
  • Merge sort: guaranteed O(n log n), O(n) space, good for linked lists and external sorting.
  • Quick sort: fastest in practice, O(n^2) worst; randomize the pivot.
  • Insertion sort is best for small or nearly sorted inputs.
  • Binary search needs a monotonic condition; use lo + (hi - lo) // 2.
  • Binary search on answer: monotonic feasibility plus a greedy check.