Sort [3, 1, 2, 4, 5] with bubble sort using a swap flag. How many comparisons are made, and how many would be made without the flag?
Sorting arranges records by key. The classic algorithms trade time, memory and stability: O(n²) bubble, selection and insertion sort; Shell sort; O(n log n) merge, quick and heap sort; and linear-time counting, radix and bucket sort for restricted keys.
Sorting arranges a collection of records in non-decreasing (or non-increasing) order of a key field. It is everywhere because sorted data is easier to use: binary search needs it, duplicates become adjacent, two sorted lists merge in linear time, and reports and rankings read naturally. The algorithms are judged on more than speed, using the properties below.
| Property | Meaning | Examples |
|---|---|---|
| Internal vs external | all data in main memory vs data on disk, sorted in chunks | quick sort is internal; multiway merge sort is external |
| In-place | only O(1) (or O(log n) stack) extra memory | insertion, selection, heap, quick sort |
| Stable | records with equal keys keep their original relative order | bubble, insertion, merge, counting, radix |
| Adaptive | runs faster on input that is already nearly sorted | insertion sort, bubble sort with a swap flag |
| Online | can sort data as it arrives, one item at a time | insertion sort |
| Comparison vs distribution | decides order only by comparing keys vs uses the key's digits or value | merge, quick, heap vs counting, radix, bucket |
Why stability matters. Sort a class list by name, then sort it again by marks with a stable algorithm: students with equal marks remain in alphabetical order. An unstable second sort may scramble them. Radix sort depends on this property, since each pass must preserve the order produced by the earlier passes.
An inversion is a pair of positions i < j with a[i] > a[j]. A sorted array has 0 inversions and a reverse-sorted one has the maximum, n(n − 1)/2. Every adjacent swap removes exactly one inversion, which is why bubble sort's swaps and insertion sort's shifts both equal the number of inversions.
Bubble sort compares adjacent pairs and swaps those that are out of order; after pass k the k largest keys have ‘bubbled’ to the end, so each pass can stop one position earlier. At most n − 1 passes are needed. Without an early exit it always makes n(n − 1)/2 comparisons; with a swapped flag it stops after the first pass that makes no swap, so an already sorted array costs only n − 1 comparisons — O(n).
Selection sort finds the smallest key of the unsorted part and swaps it into the first unsorted position. It always makes n(n − 1)/2 comparisons, whatever the input, but at most n − 1 swaps — the fewest data movements of the simple sorts, useful when writes are expensive. The long-distance swap makes the usual array version unstable, and it is not adaptive.
Insertion sort grows a sorted prefix: take the next key, shift the larger keys of the prefix one place right, and drop the key into the gap — exactly how a hand of cards is sorted. It needs n − 1 comparisons on sorted input, n(n − 1)/2 on reverse-sorted input, and its shifts equal the number of inversions. It is stable, adaptive and online, and so fast on small or nearly sorted arrays that hybrid algorithms (Timsort, introsort) use it for short pieces.
#include <stdio.h>
void show(const char *label, const int a[], int n) {
printf("%-10s", label);
for (int i = 0; i < n; i++) printf(" %d", a[i]);
printf("\n");
}
void bubbleSort(int a[], int n) { /* stable; adaptive with the flag */
for (int pass = 0; pass < n - 1; pass++) {
int swapped = 0;
for (int j = 0; j < n - 1 - pass; j++) /* the last 'pass' keys are in place */
if (a[j] > a[j + 1]) { int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t; swapped = 1; }
if (!swapped) break; /* no swap in a pass: sorted, stop */
}
}
void selectionSort(int a[], int n) { /* at most n - 1 swaps; not stable */
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++)
if (a[j] < a[min]) min = j;
if (min != i) { int t = a[i]; a[i] = a[min]; a[min] = t; }
}
}
void insertionSort(int a[], int n) { /* stable, adaptive, online */
for (int i = 1; i < n; i++) {
int key = a[i], j = i - 1;
while (j >= 0 && a[j] > key) { a[j + 1] = a[j]; j--; } /* shift larger keys right */
a[j + 1] = key;
}
}
int main(void) {
int a[] = {5, 2, 9, 1, 6}, b[] = {5, 2, 9, 1, 6}, c[] = {5, 2, 9, 1, 6};
bubbleSort(a, 5); show("bubble", a, 5);
selectionSort(b, 5); show("selection", b, 5);
insertionSort(c, 5); show("insertion", c, 5); /* each prints 1 2 5 6 9 */
return 0;
}| Pass | Bubble sort (with flag) | Selection sort | Insertion sort |
|---|---|---|---|
| 1 | 2 5 1 6 9 — 4 comparisons, 3 swaps | 1 2 9 5 6 — min 1 swapped to the front | 2 5 9 1 6 — key 2, 1 shift |
| 2 | 2 1 5 6 9 — 3 comparisons, 1 swap | 1 2 9 5 6 — 2 already in place, no swap | 2 5 9 1 6 — key 9, 0 shifts |
| 3 | 1 2 5 6 9 — 2 comparisons, 1 swap | 1 2 5 9 6 — min 5 swapped in | 1 2 5 9 6 — key 1, 3 shifts |
| 4 | 1 2 5 6 9 — 1 comparison, 0 swaps | 1 2 5 6 9 — min 6 swapped in | 1 2 5 6 9 — key 6, 1 shift |
| Total | 10 comparisons, 5 swaps | 10 comparisons, 3 swaps | 7 comparisons, 5 shifts |
Insertion sort is slow because it moves keys only one position at a time. Shell sort (Donald Shell, 1959) first insertion-sorts keys that are a large gap apart, so a key can jump far towards its destination in one move, then repeats with smaller gaps. The last pass uses gap 1 — an ordinary insertion sort — but by then the array is nearly sorted, so it is fast. It is in place but not stable.
| Gap | Groups sorted (positions gap apart) | Array afterwards |
|---|---|---|
| start | — | 23 29 15 19 31 7 9 5 |
| 4 | (23, 31) (29, 7) (15, 9) (19, 5) | 23 7 9 5 31 29 15 19 |
| 2 | (23, 9, 31, 15) and (7, 5, 29, 19) | 9 5 15 7 23 19 31 29 |
| 1 | ordinary insertion sort on a nearly sorted array | 5 7 9 15 19 23 29 31 |
#include <stdio.h>
void shellSort(int a[], int n) {
for (int gap = n / 2; gap > 0; gap /= 2) /* Shell's gaps n/2, n/4, ..., 1 */
for (int i = gap; i < n; i++) { /* insertion sort with step 'gap' */
int t = a[i], j = i;
while (j >= gap && a[j - gap] > t) { a[j] = a[j - gap]; j -= gap; }
a[j] = t;
}
}
int main(void) {
int a[] = {23, 29, 15, 19, 31, 7, 9, 5};
shellSort(a, 8); /* gaps 4, 2, 1 */
for (int i = 0; i < 8; i++) printf("%d ", a[i]);
printf("\n"); /* 5 7 9 15 19 23 29 31 */
return 0;
}The running time depends on the gap sequence: Shell's halving gaps have an O(n²) worst case, Hibbard's 1, 3, 7, 15, … (2ᵏ − 1) give O(n^1.5), Knuth's 1, 4, 13, 40, … ((3ᵏ − 1)/2) are a popular practical choice, and Pratt's gaps 2ⁱ3ʲ give O(n log² n). For many sequences the exact average complexity is still unknown — Shell sort is the classic example of a simple algorithm that is hard to analyse.
Merge sort (John von Neumann, 1945) is the textbook divide-and-conquer algorithm: split the array into two halves, sort each half recursively, then merge the two sorted halves by repeatedly taking the smaller front element. Merging runs with n elements in total costs at most n − 1 comparisons, so T(n) = 2T(n/2) + n, giving Θ(n log n) in the best, average and worst cases.
| Level | Sorted runs after merging at this level |
|---|---|
| start (8 runs of 1) | 6 | 3 | 8 | 2 | 7 | 1 | 5 | 4 |
| merge pairs | 3 6 | 2 8 | 1 7 | 4 5 |
| merge pairs of pairs | 2 3 6 8 | 1 4 5 7 |
| final merge | 1 2 3 4 5 6 7 8 |
#include <stdio.h>
#include <string.h>
void merge(int a[], int lo, int mid, int hi, int tmp[]) {
int i = lo, j = mid + 1, k = lo;
while (i <= mid && j <= hi)
tmp[k++] = (a[i] <= a[j]) ? a[i++] : a[j++]; /* <= takes the left key on ties: stable */
while (i <= mid) tmp[k++] = a[i++];
while (j <= hi) tmp[k++] = a[j++];
memcpy(&a[lo], &tmp[lo], (size_t)(hi - lo + 1) * sizeof a[0]);
}
void mergeSort(int a[], int lo, int hi, int tmp[]) { /* T(n) = 2T(n/2) + n */
if (lo >= hi) return;
int mid = lo + (hi - lo) / 2;
mergeSort(a, lo, mid, tmp);
mergeSort(a, mid + 1, hi, tmp);
merge(a, lo, mid, hi, tmp);
}
int main(void) {
int a[] = {6, 3, 8, 2, 7, 1, 5, 4}, tmp[8];
mergeSort(a, 0, 7, tmp);
for (int i = 0; i < 8; i++) printf("%d ", a[i]);
printf("\n"); /* 1 2 3 4 5 6 7 8 */
return 0;
}Quick sort (Tony Hoare, 1959) also divides and conquers, but does its work before recursing: choose a pivot key, partition the array so that keys ≤ pivot come before keys ≥ pivot, then sort the two parts recursively. No merge step is needed. It sorts in place and is usually the fastest comparison sort in practice, but it is not stable.
| j | a[j] | a[j] ≤ 5? | Action | Array |
|---|---|---|---|---|
| 0 | 9 | no | — | 9 4 7 3 10 5 |
| 1 | 4 | yes | i = 0, swap a[0], a[1] | 4 9 7 3 10 5 |
| 2 | 7 | no | — | 4 9 7 3 10 5 |
| 3 | 3 | yes | i = 1, swap a[1], a[3] | 4 3 7 9 10 5 |
| 4 | 10 | no | — | 4 3 7 9 10 5 |
| end | swap a[2] with the pivot | 4 3 5 9 10 7 — pivot fixed at index 2 |
Hoare's original partition takes the first element as pivot and moves two indices towards each other: i stops at a key ≥ pivot, j stops at a key ≤ pivot, and the two keys are swapped; when the indices cross, j is returned. For [5, 3, 8, 4, 9, 1, 6, 2, 7] (pivot 5) it swaps 5↔2 and 8↔1 and returns j = 3, leaving [2, 3, 1, 4 | 9, 8, 6, 5, 7]. It makes about three times fewer swaps than Lomuto, but the pivot is not necessarily in its final place, so the recursion is on a[lo … j] and a[j + 1 … hi]. Many Indian textbooks use a variant that finishes by swapping the pivot into a[j]: the same array becomes [1, 3, 2, 4, 5, 9, 6, 8, 7] with 5 fixed at index 4.
#include <stdio.h>
void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }
int lomuto(int a[], int lo, int hi) { /* pivot = last element */
int pivot = a[hi], i = lo - 1;
for (int j = lo; j < hi; j++)
if (a[j] <= pivot) { i++; swap(&a[i], &a[j]); }
swap(&a[i + 1], &a[hi]); /* pivot to its final position */
return i + 1;
}
int hoare(int a[], int lo, int hi) { /* pivot = first element */
int pivot = a[lo], i = lo - 1, j = hi + 1;
for (;;) {
do i++; while (a[i] < pivot);
do j--; while (a[j] > pivot);
if (i >= j) return j; /* a[lo..j] <= pivot <= a[j+1..hi] */
swap(&a[i], &a[j]);
}
}
void quickSortL(int a[], int lo, int hi) {
if (lo < hi) { int p = lomuto(a, lo, hi); quickSortL(a, lo, p - 1); quickSortL(a, p + 1, hi); }
}
void quickSortH(int a[], int lo, int hi) {
if (lo < hi) { int p = hoare(a, lo, hi); quickSortH(a, lo, p); quickSortH(a, p + 1, hi); }
}
int main(void) {
int a[] = {9, 4, 7, 3, 10, 5}, b[] = {5, 3, 8, 4, 9, 1, 6, 2, 7};
quickSortL(a, 0, 5);
quickSortH(b, 0, 8);
for (int i = 0; i < 6; i++) printf("%d ", a[i]);
printf("| ");
for (int i = 0; i < 9; i++) printf("%d ", b[i]);
printf("\n"); /* 3 4 5 7 9 10 | 1 2 3 4 5 6 7 8 9 */
return 0;
}Analysis. If every partition splits the array roughly in half, T(n) = 2T(n/2) + n = Θ(n log n); a random pivot gives this on average, with about 1.39 n log₂ n comparisons. The worst case happens when the pivot is always the smallest or largest key, so one side is empty: T(n) = T(n − 1) + (n − 1), i.e. n(n − 1)/2 comparisons — Θ(n²). With a first- or last-element pivot this is triggered by input that is already sorted or reverse sorted (and, with Lomuto, by an array of equal keys). The recursion can then also be n deep, so implementations recurse on the smaller part first, which caps the stack at O(log n).
| Strategy | Advantage | Risk |
|---|---|---|
| First or last element | simplest | Θ(n²) on sorted or reverse-sorted input |
| Random element | expected O(n log n) for every input | needs a random-number generator; worst case still possible, just very unlikely |
| Median of three (first, middle, last) | defeats sorted input cheaply; common in practice | contrived inputs can still be bad |
| Median of medians | guaranteed O(n log n) | large constant factor, rarely used |
std::sort is typically introsort (David Musser, 1997): quick sort that switches to heap sort if the recursion gets too deep, and to insertion sort for small pieces — keeping quick sort's speed with an O(n log n) guarantee. The selected partitioning key is called the pivot (older books say pivot key).Heap sort (J. W. J. Williams, 1964, with Floyd's bottom-up construction) uses the binary max-heap from the priority-queue topic. Phase 1 turns the array into a max-heap in O(n). Phase 2 repeatedly swaps the maximum (the root) with the last element of the heap, shrinks the heap by one, and sifts the new root down — n − 1 rounds of O(log n). Total Θ(n log n) in every case with O(1) extra space, but it is not stable and its scattered memory accesses make it slower than quick sort in practice.
| Step | Heap part (array prefix) | Sorted part (array suffix) |
|---|---|---|
| build max-heap | 10 5 3 4 1 | — |
| swap 10 to the end, sift down | 5 4 3 1 | 10 |
| swap 5 to the end, sift down | 4 1 3 | 5 10 |
| swap 4 to the end, sift down | 3 1 | 4 5 10 |
| swap 3 to the end | 1 | 3 4 5 10 |
| done | 1 3 4 5 10 |
#include <stdio.h>
void siftDown(int a[], int i, int n) { /* max-heap of size n, 0-based */
for (;;) {
int l = 2 * i + 1, r = 2 * i + 2, big = i;
if (l < n && a[l] > a[big]) big = l;
if (r < n && a[r] > a[big]) big = r;
if (big == i) return;
int t = a[i]; a[i] = a[big]; a[big] = t;
i = big;
}
}
void heapSort(int a[], int n) {
for (int i = n / 2 - 1; i >= 0; i--) siftDown(a, i, n); /* build max-heap: O(n) */
for (int end = n - 1; end > 0; end--) {
int t = a[0]; a[0] = a[end]; a[end] = t; /* largest key to the back */
siftDown(a, 0, end); /* heap shrinks by one */
}
}
int main(void) {
int a[] = {4, 10, 3, 5, 1};
heapSort(a, 5);
for (int i = 0; i < 5; i++) printf("%d ", a[i]);
printf("\n"); /* 1 3 4 5 10 */
return 0;
}Comparison sorts cannot beat Ω(n log n) (see the next section), but if keys have extra structure — small integers, fixed-length digit strings, uniformly spread real numbers — we can sort without comparing keys at all.
| Value v | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| count[v] | 1 | 2 | 1 | 2 | 2 |
| after prefix sums | 1 | 3 | 4 | 6 | 8 |
| output block (positions) | 0 | 1–2 | 3 | 4–5 | 6–7 |
Output: 0 1 1 2 3 3 4 4. Radix sort (LSD) sorts d-digit keys one digit at a time, from the least significant digit to the most significant, using a stable sort such as counting sort for each digit. Because each pass is stable, keys that tie on the current digit keep the order fixed by the less significant digits. With base b the cost is O(d(n + b)). The idea goes back to Herman Hollerith's punched-card machines of the late 1880s, built for the 1890 US census.
| Pass | Digit used | Order after the pass |
|---|---|---|
| 1 | units | 130 51 312 263 205 47 7 98 |
| 2 | tens | 205 7 312 130 47 51 263 98 |
| 3 | hundreds | 7 47 51 98 130 205 263 312 |
Bucket sort suits keys spread uniformly over [0, 1): create n buckets, put key x into bucket ⌊n·x⌋, sort each bucket (insertion sort) and concatenate. With 10 buckets, [0.42, 0.32, 0.23, 0.52, 0.25, 0.47, 0.51] lands as bucket 2: 0.23, 0.25; bucket 3: 0.32; bucket 4: 0.42, 0.47; bucket 5: 0.51, 0.52. The average cost is O(n); if every key falls into one bucket it degrades to O(n²).
#include <stdio.h>
#include <string.h>
#define MAXN 64
void countingSort(int a[], int n, int k) { /* keys in 0..k, k < 100 */
int count[100] = {0}, out[MAXN];
for (int i = 0; i < n; i++) count[a[i]]++;
for (int v = 1; v <= k; v++) count[v] += count[v - 1]; /* prefix sums */
for (int i = n - 1; i >= 0; i--) out[--count[a[i]]] = a[i]; /* right to left: stable */
memcpy(a, out, (size_t)n * sizeof a[0]);
}
void sortByDigit(int a[], int n, int exp) { /* stable counting sort on one digit */
int count[10] = {0}, out[MAXN];
for (int i = 0; i < n; i++) count[(a[i] / exp) % 10]++;
for (int d = 1; d < 10; d++) count[d] += count[d - 1];
for (int i = n - 1; i >= 0; i--) out[--count[(a[i] / exp) % 10]] = a[i];
memcpy(a, out, (size_t)n * sizeof a[0]);
}
void radixSort(int a[], int n) { /* least significant digit first */
int max = a[0];
for (int i = 1; i < n; i++) if (a[i] > max) max = a[i];
for (int exp = 1; max / exp > 0; exp *= 10) sortByDigit(a, n, exp);
}
int main(void) {
int c[] = {4, 1, 3, 4, 2, 1, 0, 3};
countingSort(c, 8, 4);
for (int i = 0; i < 8; i++) printf("%d ", c[i]);
printf("\n"); /* 0 1 1 2 3 3 4 4 */
int r[] = {312, 47, 205, 98, 130, 51, 7, 263};
radixSort(r, 8);
for (int i = 0; i < 8; i++) printf("%d ", r[i]);
printf("\n"); /* 7 47 51 98 130 205 263 312 */
return 0;
}| Algorithm | Best | Average | Worst | Extra space | Stable | In place |
|---|---|---|---|---|---|---|
| Bubble (with flag) | n | n² | n² | O(1) | yes | yes |
| Selection | n² | n² | n² | O(1) | no | yes |
| Insertion | n | n² | n² | O(1) | yes | yes |
| Shell | n log n | depends on gaps (≈ n^1.25 – n^1.5) | n² (Shell's gaps), n^1.5 (Hibbard) | O(1) | no | yes |
| Merge | n log n | n log n | n log n | O(n) | yes | no |
| Quick | n log n | n log n | n² | O(log n) stack | no | yes |
| Heap | n log n | n log n | n log n | O(1) | no | yes |
| Counting | n + k | n + k | n + k | O(n + k) | yes | no |
| Radix (LSD) | d(n + b) | d(n + b) | d(n + b) | O(n + b) | yes | no |
| Bucket | n | n | n² | O(n) | yes, if buckets are sorted stably | no |
The lower bound. Any comparison sort can be drawn as a binary decision tree: each internal node compares two keys and each leaf is one possible output order. All n! orders must appear as leaves, and a binary tree of height h has at most 2ʰ leaves, so h ≥ log₂(n!) = Θ(n log n). Hence every comparison sort needs Ω(n log n) comparisons in the worst case, and merge sort and heap sort are asymptotically optimal. The bound ⌈log₂ n!⌉ is 3 for 3 keys, 5 for 4 keys and 7 for 5 keys — and those numbers can actually be achieved.
External sorting handles files too large for main memory. Phase 1 reads memory-sized chunks, sorts each internally and writes them back as sorted runs (replacement selection with a heap produces runs about twice the memory size on random data). Phase 2 performs a k-way merge of the runs, using a min-heap of the k current run heads; r runs need ⌈log_k r⌉ merge passes. Polyphase merging minimises tape rewinds. Because it reads and writes data sequentially, merge sort is the standard external sorting method.
Try the problem first, then reveal the working one step at a time.
Sort [3, 1, 2, 4, 5] with bubble sort using a swap flag. How many comparisons are made, and how many would be made without the flag?
Sort [9, 4, 7, 3, 10, 5] with quick sort (last element as pivot). Show each partition and count the key comparisons.
Quick sort with the last element as pivot is run on the already sorted array [1, 2, 3, 4, 5]. Count the comparisons and the recursion depth.
Sort the records (3, a), (1, b), (3, c), (2, d) by their numeric key with selection sort and with insertion sort. Which result is stable?
Trace insertion sort on [8, 4, 6, 2, 9]. Give the array after each insertion, the total comparisons and shifts, and relate the shifts to the inversions.
Apply one Lomuto partition (pivot = last element) to [3, 8, 2, 5, 1, 4, 7, 6]. Where does the pivot end up?
For n = 10 keys, how many comparisons does selection sort make, and what is the maximum number of swaps? How many comparisons does bubble sort without a flag make?
What is the minimum number of comparisons any comparison sort needs in the worst case to sort (a) 5 keys, (b) 6 keys?
Choose the most suitable algorithm and justify it: (a) 1 million records arriving in nearly sorted order; (b) a 50 GB log file on a machine with 4 GB of RAM; (c) a guaranteed O(n log n) in-place sort; (d) sorting 10 million exam marks in the range 0–100.
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.