BTI Beyond The Interviews

DSA · 10 sections

Sorting Algorithms

Comparison sorts, non-comparison sorts, and when to use which — the DSA interview core.

Free · full sheet 126 cards Updated 24 Oct 2026

Bubble Sort

How does bubble sort work?

Repeatedly swap adjacent out-of-order pairs; largest bubbles to the end each pass. O(n²) worst/avg, O(n) best (with early exit).

Bubble sort code.

Two nested loops compare adjacent pairs and swap when out of order, shrinking the inner bound by one each pass. A swapped flag lets an already sorted array exit after a single pass.

for i in range(n):
  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

Bubble sort time complexity.

Worst/average O(n²), best O(n) with early termination. Comparisons always O(n²) without optimization.

Bubble sort space complexity.

O(1) extra space: bubble sort works in place, using only a temporary for the swap and a boolean flag. No auxiliary array or recursion stack is involved.

Is bubble sort stable?

Yes — only swaps strictly greater elements, preserving equal-key order.

When is bubble sort useful?

Almost never in production; used for teaching or detecting if array is already sorted (one pass).

Cocktail shaker sort.

Bidirectional bubble sort; bubbles both largest and smallest. Same complexity, slightly better constant.

Odd-even sort.

Parallel-friendly bubble variant; compares odd/even index pairs in alternating phases.

Bubble sort on nearly sorted data.

O(n) with early exit if already sorted; otherwise still O(n²) for few inversions.

Number of passes in bubble sort.

At most n-1 passes, because each full pass moves the largest remaining element into its final position. With the early-exit flag it can stop after one pass on already sorted input.

Bubble sort swap count equals inversion count.

Each swap exchanges one adjacent inverted pair and removes exactly one inversion, and no other step changes the inversion count. So total swaps equal inversions: 0 when sorted, n(n-1)/2 when reversed.

Selection Sort

How does selection sort work?

Find minimum in unsorted suffix, swap with first unsorted position. O(n²) time always, O(1) space.

Selection sort code.

The outer loop walks each position while the inner loop scans the unsorted suffix for the minimum index, then one swap places it. Exactly n-1 swaps, but O(n^2) comparisons whatever the input order.

for i in range(n):
  mn=i
  for j in range(i+1,n):
    if a[j]<a[mn]: mn=j
  a[i],a[mn]=a[mn],a[i]

Selection sort time complexity.

Theta(n^2) in the best, average and worst cases, because the inner loop always scans the whole suffix, so pre-sorted input saves nothing. It is not adaptive, though it performs only O(n) swaps.

Selection sort space complexity.

O(1) extra space: it sorts in place with a couple of index variables and one swap temporary. No auxiliary array or recursion stack is needed.

Is selection sort stable?

No by default (swaps can jump over equal keys). Can be made stable with insertion instead of swap.

Selection sort write count.

Only O(n) writes (one swap per pass) — useful when writes are expensive (flash memory).

Heap sort relation.

Heap sort is an efficient selection sort: use a heap to find min/max in O(log n) instead of O(n).

When to use selection sort?

Tiny arrays or when write cost dominates; otherwise insertion/merge/quick better.

Selection sort vs insertion sort.

Selection does fewer writes but more comparisons; insertion better for nearly sorted data.

Double selection sort.

Find both min and max each pass, placing two elements. ~n²/4 comparisons.

Selection sort on linked lists?

O(n²) with pointer swaps; still poor; merge sort preferred for linked lists.

Is selection sort online?

No. Each pass must scan the entire remaining input to find the global minimum, so no element can be committed until all data has arrived. Insertion sort, by contrast, is online.

Insertion Sort

How does insertion sort work?

Build sorted prefix by inserting each next element into its correct position via shifting. O(n²) worst, O(n) best.

Insertion sort code.

Save a[i] as the key, shift every larger element of the sorted prefix one slot right, then drop the key into the gap. The shift stops at the first element <= key, which keeps the sort stable.

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

Insertion sort time complexity.

Worst/average O(n²), best O(n) (already sorted). Comparisons = inversions + (n-1).

Insertion sort space complexity.

O(1) extra space: it reorders in place by shifting elements inside the array, holding only the current key and an index. No auxiliary buffer and no recursion stack.

Is insertion sort stable?

Yes. The inner loop shifts only while a[j] > key, a strict comparison, so equal elements are never moved past each other and their relative order survives.

Why insertion sort for small arrays?

Low overhead and cache-friendly; used as base case in Timsort (minrun 32-64) and Introsort (cutoff ~16).

Insertion sort on nearly sorted data.

Cost is O(n + d) where d is the number of inversions, since each element moves at most the count of larger elements before it. When d is O(n) the sort is effectively linear.

Binary insertion sort.

Use binary search to find insertion position; reduces comparisons to O(n log n) but shifts still O(n²).

Insertion sort on linked lists.

It runs in O(n^2) time with O(1) extra space and stays stable, but the absence of random access and the pointer rewriting make it slow. Merge sort is the usual choice for linked lists.

Shell sort.

Insertion sort with gaps; improves to ~O(n^1.5) depending on gap sequence. In-place, not stable.

When does insertion sort beat merge/quick?

On small arrays, roughly n < 16-50, its low overhead and cache locality beat the recursion and allocation of merge or quick. It also wins on nearly sorted data, which is why hybrids switch to it.

Merge Sort

How does merge sort work?

Divide array in half, recursively sort, then merge two sorted halves with two pointers. O(n log n) all cases.

Merge sort code.

Split at the midpoint, sort both halves recursively, then merge with two pointers that repeatedly take the smaller head. Taking from the left half on ties keeps the sort stable.

def merge_sort(a):
  if len(a)<=1: return a
  mid=len(a)//2
  L=merge_sort(a[:mid]); R=merge_sort(a[mid:])
  return merge(L,R)  # two-pointer merge

Merge sort time complexity.

Theta(n log n) in all cases from T(n) = 2T(n/2) + O(n): log n levels, each doing linear merge work. Input order changes the constants but not the bound.

Merge sort space complexity.

O(n) for the auxiliary buffer used while merging, plus O(log n) recursion depth. The linked-list variant drops the buffer to O(1) but keeps the stack unless it is written bottom-up.

Is merge sort stable?

Yes — when merging, take from left half on equality, preserving order.

Why merge sort for linked lists?

O(1) extra space (just pointers), stable, and no random access needed. Preferred over quick.

External merge sort.

Sort chunks that fit in memory, then multi-way merge from disk. Standard for large datasets.

Bottom-up (iterative) merge sort.

Merge runs of size 1,2,4,...; avoids recursion; same complexity, better cache in some cases.

Merge sort vs quick sort.

Merge: stable, guaranteed O(n log n), O(n) space. Quick: in-place, faster average, unstable, O(n²) worst.

In-place merge sort?

Possible but complex (rotations); usually not worth it. Standard uses O(n) auxiliary.

Counting inversions with merge sort.

During merge, when taking from right half, add remaining left count to inversions. O(n log n).

Merge step correctness.

Two pointers walk the sorted halves, repeatedly appending the smaller current element, then copy the remainder of whichever half is left. Each element is written once, so a merge is linear in the total length.

Merge k sorted lists.

Min-heap of list heads runs in O(N log k) for N total elements; divide-and-conquer pairwise merge is an alternative. Basis of external merge sort.

import heapq
heap=[(lst[0],i,0) for i,lst in enumerate(lists) if lst]
heapq.heapify(heap)
out=[]
while heap:
  v,i,j=heapq.heappop(heap); out.append(v)
  if j+1<len(lists[i]): heapq.heappush(heap,(lists[i][j+1],i,j+1))

Sorting a linked list (merge sort).

Bottom-up or recursive merge sort with pointer rewiring; O(n log n) time, O(1) extra (iterative) or O(log n) stack (recursive); stable.

def sort_list(head):
  if not head or not head.next: return head
  slow,fast=head,head.next
  while fast and fast.next:
    slow=slow.next; fast=fast.next.next
  mid=slow.next; slow.next=None
  return merge(sort_list(head), sort_list(mid))

Quick Sort

How does quick sort work?

Pick pivot, partition into <pivot and >pivot, recurse. Average O(n log n), worst O(n²).

Quick sort code.

Partition around a pivot, then recurse on the left and right subarrays. The partition returns the pivot's final index, which is excluded from both recursive calls.

def qs(a,lo,hi):
  if lo<hi:
    p=partition(a,lo,hi)
    qs(a,lo,p-1); qs(a,p+1,hi)

Lomuto partition scheme.

Pivot = last element; i tracks boundary of <=pivot; swap on <=. Returns pivot index. Simple but more swaps.

Hoare partition scheme.

Two indices scan inward from both ends; more efficient (fewer swaps) but pivot not necessarily in final position. Standard in practice.

Pivot selection strategies.

First/last (bad for sorted), middle, median-of-three, random. Randomized gives expected O(n log n).

Quick sort worst case.

O(n²) when pivot is always min/max (sorted input with first/last pivot). Fix with random/median pivot.

Quick sort space complexity.

O(log n) average stack, O(n) worst (degenerate). Recurse on the smaller partition and loop on the larger one to guarantee O(log n) worst-case stack; tail-call optimization alone does not bound stack.

Is quick sort stable?

No. Lomuto and Hoare partitioning swap elements across long distances, so equal keys can change relative order. Use merge sort, or decorate elements with their original index, when stability matters.

Randomized quick sort.

Pick random pivot; expected O(n log n) for any input; avoids adversarial worst cases.

3-way quick sort (Dutch national flag).

Partition into <, =, >; great for many duplicates. O(n) for few distinct keys.

Introsort.

Quick sort that switches to heap sort if recursion depth exceeds 2 log n; guarantees O(n log n). Used in C++ std::sort.

Quick sort vs merge sort in practice.

Quick has better cache locality and lower constant; merge stable and guaranteed. Most std libs use hybrid (Introsort/Timsort).

Quickselect (k-th smallest element).

Partition like quicksort but recurse on only one side; average O(n), worst O(n^2). Randomized or median-of-medians gives guaranteed linear time.

def quickselect(a, k, lo=0, hi=None):
  if hi is None: hi=len(a)-1
  if lo==hi: return a[lo]
  p=partition(a, lo, hi)
  if k==p: return a[p]
  if k<p: return quickselect(a, k, lo, p-1)
  return quickselect(a, k, p+1, hi)

pdqsort (pattern-defeating quicksort).

Hybrid quicksort with pattern detection and heap fallback; O(n log n) worst, O(n) on sorted/reverse-sorted input. Used in Go (1.19+) and Rust (driftsort/ipnsort in 1.81+).

Heap Sort

How does heap sort work?

Build max-heap, then repeatedly extract max to end. O(n log n) all cases, O(1) space.

Heap sort code.

Build a max-heap in O(n), then for each index from the end swap the root with it and sift down over the shrinking heap. The sorted suffix grows from the back, so the array ends up ascending.

build_max_heap(a)
for i in range(n-1,0,-1):
  a[0],a[i]=a[i],a[0]
  sift_down(a,0,i)

Build heap complexity.

O(n) bottom-up (not O(n log n)). sift_down from last non-leaf up to root.

Heap sort time complexity.

Theta(n log n) in all cases: O(n) to build the heap plus n extractions at O(log n) each. Unlike quicksort, sorted or reverse-sorted input does not degrade it.

Heap sort space complexity.

O(1) auxiliary space when sift-down is written iteratively, since it sorts inside the input array and needs only index temporaries. A recursive sift-down costs O(log n) stack instead.

Is heap sort stable?

No. Sift-down swaps a node with a child that is far away in the array, so equal keys can be reordered. Sorting records by one field while preserving another needs a stable sort such as merge sort.

When to use heap sort?

When O(1) space and guaranteed O(n log n) are needed; e.g. embedded systems. Otherwise quick/merge faster in practice.

Max-heap vs min-heap for sorting.

Max-heap sorts ascending (extract max to end); min-heap sorts descending.

Heap sort vs quick sort speed.

Heap has worse cache locality than quick; quick usually faster in practice despite worse worst case.

Partial heap sort / top-k.

Build heap and extract k times for top-k in O(n + k log n); or use min-heap of size k O(n log k).

Heapify (sift down) correctness.

Compare node with children, swap with larger child, recurse until heap property restored.

Heapsort is not adaptive.

It runs in Theta(n log n) even on fully sorted or reverse-sorted input, with no early exit. That predictability is exactly why introsort uses it as a fallback.

Partial sort / nth_element.

Place the first k elements in sorted order; the rest are unspecified. O(n log k) via a heap, or O(n) average via quickselect. C++: std::partial_sort, std::nth_element.

Non-Comparison Sorts

Counting sort.

Count occurrences, prefix sum for positions, place elements. O(n+k) time, O(n+k) space. Stable. Small integer ranges.

Counting sort code.

Count each key, prefix-sum the counts into end positions, then place elements from right to left so equal keys keep their input order. Decrementing the position after each placement is what makes it stable.

cnt=[0]*(k+1)
for x in a: cnt[x]+=1
for i in range(1,k+1): cnt[i]+=cnt[i-1]
for x in reversed(a):
  out[cnt[x]-1]=x; cnt[x]-=1

Radix sort.

Sort by digits (LSD or MSD) using counting sort per digit. O(d(n+k)). Good for fixed-width ints/strings.

LSD vs MSD radix sort.

LSD processes least significant digit first; stable, simpler. MSD most significant first; can be recursive/in-place-ish, good for strings.

Bucket sort.

Distribute into buckets by value, sort each bucket. O(n) average if uniform; O(n²) worst. Used for floats.

When are non-comparison sorts better?

When key range k is O(n) or digits d small; beat Ω(n log n) comparison lower bound.

Limitations of counting sort.

Key range k must be manageable: you can offset by min(a), so non-negativity is not the limit; memory is O(k). Not suitable for huge ranges or floats.

Radix sort for strings.

MSD radix sort with buckets per character; efficient for variable-length strings.

Bucket sort for floats in [0,1).

n buckets of size 1/n; distribute, sort each (insertion), concatenate. Expected O(n).

Stability of non-comparison sorts.

Counting sort stable; radix requires stable per-digit sort; bucket sort stable if inner sort stable.

Pigeonhole sort.

Like counting sort but places each item in its pigeonhole list; stable variant.

Flashsort.

Distribution sort based on value; O(n) average, in-place-ish; complex.

Stability & Properties

Stable vs unstable sort.

Stable preserves relative order of equal keys; unstable may reorder them.

When does stability matter?

Multi-key sorting (sort by secondary then primary), and when original order carries meaning (stable sort of records by a field).

How to make an unstable sort stable?

Augment each element with original index and compare index on ties. Costs O(n) space and time.

Adaptive sort.

Runs faster on partially ordered input. Insertion and Timsort are adaptive; merge/heap/quick not.

Online sort.

Can process elements as they arrive. Insertion sort is online; most need all data.

In-place sort.

Uses O(1) extra memory. Quick, heap, insertion, selection, bubble are in-place.

Comparison-based lower bound Ω(n log n).

A comparison sort is a binary decision tree with n! leaves, one per permutation of the input. Its height is at least log2(n!), which is Theta(n log n), so no comparison sort beats that in the worst case.

Timsort.

Hybrid: insertion sort on small runs + merge sort. Stable, O(n log n) worst, O(n) best; minrun 32-64. Defaults: Python list.sort (Timsort; merge policy Powersort since 3.11+), Java (objects only; primitives use dual-pivot quicksort). Rust uses driftsort/ipnsort (1.81+); Go uses pdqsort (1.19+).

Smoothsort.

Heap sort variant with O(n) best case on sorted data; complex, rarely used.

Block sort.

An in-place stable merge sort that merges blocks using internal buffers and rotations, giving O(n log n) time and O(1) extra space. High constants and complexity keep it rare outside specialized libraries.

Sorting with custom comparators and keys.

Sort by a key function or comparator. The comparator must define a consistent total order (transitive, antisymmetric) or results are undefined.

Comparator consistency bugs.

Inconsistent comparators (e.g., comparing different fields) violate sort invariants; in Java/Python this can raise or loop. Always define one total order; use key functions when possible.

Complexity & Lower Bounds

What is a comparison sort?

Sorts only by comparing elements; has Ω(n log n) lower bound. Examples: merge, quick, heap, insertion, selection, bubble.

Best comparison sort complexity?

O(n log n) time worst case (merge/heap). Quick sort O(n log n) average, O(n²) worst.

Space complexity of common sorts.

Merge O(n), quick O(log n) stack, heap O(1), insertion/selection/bubble O(1).

Which comparison sorts are stable?

Bubble, insertion, merge and Timsort are stable. Quick, heap and selection are not.

When to use which comparison sort?

Small/nearly sorted: insertion. General: quick (fast, in-place) or merge (stable, guaranteed). Space-tight: heap.

In-place vs out-of-place sorting.

In-place uses O(1) extra; out-of-place (merge) uses O(n). Trade memory for simplicity/stability.

Non-comparison sort advantage.

Counting/radix/bucket can beat O(n log n) when keys have bounded range or digit structure.

Best-case time complexities.

Bubble/insertion O(n); merge/heap O(n log n); quick O(n log n); counting/radix O(n+k).

Average-case time complexities.

Quick O(n log n); merge/heap O(n log n); insertion/selection/bubble O(n²); counting O(n+k).

Worst-case time complexities.

Quick O(n²); merge/heap O(n log n); insertion/selection/bubble O(n²); counting O(n+k).

When non-comparison sorts are invalid.

When keys are arbitrary/comparable only (no bounded range/digits), comparison bound applies.

Cache and constant factors.

Quick sort often fastest in practice due to cache locality and low constant, despite O(n²) worst.

Recursion depth of merge/quick.

Merge sort recurses O(log n) deep because it halves unconditionally. Quicksort is O(log n) only if you recurse into the smaller side and loop on the larger; naive first/last pivots on sorted input give O(n) depth.

Parallel sorting.

Merge sort parallelizes well (divide). Bitonic sort for GPUs. Quick sort parallelizable but load balancing tricky.

Out-of-core / external sort complexity.

O((n/B) log_{M/B}(n/B)) I/Os where M=memory, B=block size. Merge sort based.

Stability vs speed tradeoff.

Stable sorts (merge, Timsort) use extra memory; but Timsort is often faster on real-world, partly ordered data. Unstable sorts (quick, heap) are in-place and fast on random data.

Common Gotchas

Recursion depth / stack overflow.

Quick sort on sorted data with bad pivot can recurse n deep. Use randomized pivot or iterative with explicit stack.

Small arrays.

Switch to insertion sort below a threshold (Introsort ~16; Timsort minrun 32-64) for better constant factor.

Nearly sorted data.

Insertion sort runs in O(n + inversions) and Timsort detects existing runs, so both are near linear. Quicksort and heapsort gain nothing from existing order and still do full work.

Duplicates.

Many duplicates slow standard quick sort; use 3-way partition (Dutch national flag).

Stability assumptions.

Quick/heap are unstable; don't rely on original order of equal keys. Use merge/Timsort if needed.

Integer overflow in mid/index.

In fixed-width languages (lo + hi) / 2 can overflow when both indices are large, producing a negative or bogus pivot. Compute lo + (hi - lo) / 2 instead; the same care applies to index arithmetic in binary search.

Off-by-one in merge boundaries.

Ensure merge ranges [lo,mid] and [mid+1,hi] are disjoint and cover all; common bug.

In-place merge is hard.

Standard merge needs O(n) aux; naive in-place merge is O(n²) or complex.

Counting sort range.

Counting sort allocates an array of size k, the key range, so when k is far larger than n most of that memory is wasted. Fall back to a comparison sort, or compress keys first, when k >> n.

Radix sort digit order.

LSD requires stable per-digit sort; using unstable sort breaks correctness.

Assuming sort() is stable.

Language default may be unstable (C qsort). Check docs; Python/Java sort is stable.

Want this as flashcards? Study these 126 cards recall-first in the browser — flip, answer out loud, grade yourself.

Open the card deck