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).
DSA · 10 sections
Comparison sorts, non-comparison sorts, and when to use which — the DSA interview core.
Repeatedly swap adjacent out-of-order pairs; largest bubbles to the end each pass. O(n²) worst/avg, O(n) best (with early exit).
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
Worst/average O(n²), best O(n) with early termination. Comparisons always O(n²) without optimization.
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.
Yes — only swaps strictly greater elements, preserving equal-key order.
Almost never in production; used for teaching or detecting if array is already sorted (one pass).
Bidirectional bubble sort; bubbles both largest and smallest. Same complexity, slightly better constant.
Parallel-friendly bubble variant; compares odd/even index pairs in alternating phases.
O(n) with early exit if already sorted; otherwise still O(n²) for few inversions.
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.
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.
Find minimum in unsorted suffix, swap with first unsorted position. O(n²) time always, O(1) space.
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]
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.
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.
No by default (swaps can jump over equal keys). Can be made stable with insertion instead of swap.
Only O(n) writes (one swap per pass) — useful when writes are expensive (flash memory).
Heap sort is an efficient selection sort: use a heap to find min/max in O(log n) instead of O(n).
Tiny arrays or when write cost dominates; otherwise insertion/merge/quick better.
Selection does fewer writes but more comparisons; insertion better for nearly sorted data.
Find both min and max each pass, placing two elements. ~n²/4 comparisons.
O(n²) with pointer swaps; still poor; merge sort preferred for linked lists.
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.
Build sorted prefix by inserting each next element into its correct position via shifting. O(n²) worst, O(n) best.
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
Worst/average O(n²), best O(n) (already sorted). Comparisons = inversions + (n-1).
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.
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.
Low overhead and cache-friendly; used as base case in Timsort (minrun 32-64) and Introsort (cutoff ~16).
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.
Use binary search to find insertion position; reduces comparisons to O(n log n) but shifts still O(n²).
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.
Insertion sort with gaps; improves to ~O(n^1.5) depending on gap sequence. In-place, not stable.
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.
Divide array in half, recursively sort, then merge two sorted halves with two pointers. O(n log n) all cases.
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
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.
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.
Yes — when merging, take from left half on equality, preserving order.
O(1) extra space (just pointers), stable, and no random access needed. Preferred over quick.
Sort chunks that fit in memory, then multi-way merge from disk. Standard for large datasets.
Merge runs of size 1,2,4,...; avoids recursion; same complexity, better cache in some cases.
Merge: stable, guaranteed O(n log n), O(n) space. Quick: in-place, faster average, unstable, O(n²) worst.
Possible but complex (rotations); usually not worth it. Standard uses O(n) auxiliary.
During merge, when taking from right half, add remaining left count to inversions. O(n log n).
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.
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))
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))
Pick pivot, partition into <pivot and >pivot, recurse. Average O(n log n), worst O(n²).
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)
Pivot = last element; i tracks boundary of <=pivot; swap on <=. Returns pivot index. Simple but more swaps.
Two indices scan inward from both ends; more efficient (fewer swaps) but pivot not necessarily in final position. Standard in practice.
First/last (bad for sorted), middle, median-of-three, random. Randomized gives expected O(n log n).
O(n²) when pivot is always min/max (sorted input with first/last pivot). Fix with random/median pivot.
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.
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.
Pick random pivot; expected O(n log n) for any input; avoids adversarial worst cases.
Partition into <, =, >; great for many duplicates. O(n) for few distinct keys.
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 has better cache locality and lower constant; merge stable and guaranteed. Most std libs use hybrid (Introsort/Timsort).
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)
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+).
Build max-heap, then repeatedly extract max to end. O(n log n) all cases, O(1) space.
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)
O(n) bottom-up (not O(n log n)). sift_down from last non-leaf up to root.
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.
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.
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 O(1) space and guaranteed O(n log n) are needed; e.g. embedded systems. Otherwise quick/merge faster in practice.
Max-heap sorts ascending (extract max to end); min-heap sorts descending.
Heap has worse cache locality than quick; quick usually faster in practice despite worse worst case.
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).
Compare node with children, swap with larger child, recurse until heap property restored.
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.
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.
Count occurrences, prefix sum for positions, place elements. O(n+k) time, O(n+k) space. Stable. Small integer ranges.
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
Sort by digits (LSD or MSD) using counting sort per digit. O(d(n+k)). Good for fixed-width ints/strings.
LSD processes least significant digit first; stable, simpler. MSD most significant first; can be recursive/in-place-ish, good for strings.
Distribute into buckets by value, sort each bucket. O(n) average if uniform; O(n²) worst. Used for floats.
When key range k is O(n) or digits d small; beat Ω(n log n) comparison lower bound.
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.
MSD radix sort with buckets per character; efficient for variable-length strings.
n buckets of size 1/n; distribute, sort each (insertion), concatenate. Expected O(n).
Counting sort stable; radix requires stable per-digit sort; bucket sort stable if inner sort stable.
Like counting sort but places each item in its pigeonhole list; stable variant.
Distribution sort based on value; O(n) average, in-place-ish; complex.
Stable preserves relative order of equal keys; unstable may reorder them.
Multi-key sorting (sort by secondary then primary), and when original order carries meaning (stable sort of records by a field).
Augment each element with original index and compare index on ties. Costs O(n) space and time.
Runs faster on partially ordered input. Insertion and Timsort are adaptive; merge/heap/quick not.
Can process elements as they arrive. Insertion sort is online; most need all data.
Uses O(1) extra memory. Quick, heap, insertion, selection, bubble are in-place.
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.
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+).
Heap sort variant with O(n) best case on sorted data; complex, rarely used.
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.
Sort by a key function or comparator. The comparator must define a consistent total order (transitive, antisymmetric) or results are undefined.
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.
Sorts only by comparing elements; has Ω(n log n) lower bound. Examples: merge, quick, heap, insertion, selection, bubble.
O(n log n) time worst case (merge/heap). Quick sort O(n log n) average, O(n²) worst.
Merge O(n), quick O(log n) stack, heap O(1), insertion/selection/bubble O(1).
Bubble, insertion, merge and Timsort are stable. Quick, heap and selection are not.
Small/nearly sorted: insertion. General: quick (fast, in-place) or merge (stable, guaranteed). Space-tight: heap.
In-place uses O(1) extra; out-of-place (merge) uses O(n). Trade memory for simplicity/stability.
Counting/radix/bucket can beat O(n log n) when keys have bounded range or digit structure.
Bubble/insertion O(n); merge/heap O(n log n); quick O(n log n); counting/radix O(n+k).
Quick O(n log n); merge/heap O(n log n); insertion/selection/bubble O(n²); counting O(n+k).
Quick O(n²); merge/heap O(n log n); insertion/selection/bubble O(n²); counting O(n+k).
When keys are arbitrary/comparable only (no bounded range/digits), comparison bound applies.
Quick sort often fastest in practice due to cache locality and low constant, despite O(n²) worst.
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.
Merge sort parallelizes well (divide). Bitonic sort for GPUs. Quick sort parallelizable but load balancing tricky.
O((n/B) log_{M/B}(n/B)) I/Os where M=memory, B=block size. Merge sort based.
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.
Quick sort on sorted data with bad pivot can recurse n deep. Use randomized pivot or iterative with explicit stack.
Switch to insertion sort below a threshold (Introsort ~16; Timsort minrun 32-64) for better constant factor.
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.
Many duplicates slow standard quick sort; use 3-way partition (Dutch national flag).
Quick/heap are unstable; don't rely on original order of equal keys. Use merge/Timsort if needed.
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.
Ensure merge ranges [lo,mid] and [mid+1,hi] are disjoint and cover all; common bug.
Standard merge needs O(n) aux; naive in-place merge is O(n²) or complex.
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.
LSD requires stable per-digit sort; using unstable sort breaks correctness.
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.
What's new and the interview questions people are actually getting asked. No spam.