Kodewick
Start learning →
Patterns: sorting44 / 50

Patterns: sorting

Lesson 44 of 50 · Part 8 · Sorting · about 18 minutes

This sorting review puts the time, space and stability of eight sorts in one table, shows how real C code sorts with qsort and a comparison function that can't overflow, and finds the k-th smallest in O(n) on average with quickselect.

Exams rarely ask you to "write sort X". They ask you to compare: which is stable, which stays O(n log n) even at worst, what the array looks like after one pass. Interviews like problems that "don't need a full sort". This lesson has four steps, one pattern each.

One table for every sort

SortAverageWorstBestExtra spaceStableOne pass fixes
BubbleO(n²)O(n²)O(n)O(1)stablethe largest
SelectionO(n²)O(n²)O(n²)O(1)not stablethe smallest
InsertionO(n²)O(n²)O(n)O(1)stablenothing
Shellabout O(n^1.3)O(n²)O(1)not stablenothing
MergeO(n log n)O(n log n)O(n log n)O(n)stablenothing
QuickO(n log n)O(n²)O(n log n)O(log n)not stablethe pivot
CountingO(n + k)O(n + k)O(n + k)O(k)stable
RadixO(d(n + r))O(d(n + r))O(n + r)stable

To remember: the unstable four are selection, Shell, quick and heap (heap sort, from chapter 4, isn't stable either).

Which to choose:

  • Small (a few dozen) or nearly sorted: insertion sort.
  • Must be stable, or O(n log n) even at worst, or a linked list: merge sort.
  • The general case, speed first, stability not needed: quicksort (random pivot).
  • Whole numbers in a small range: counting sort; fixed number of digits: radix sort.
Choose allPick all that apply

Which sorts are unstable? (You can pick more than one.)

How C really sorts: qsort

In real programs you don't write your own: the standard library's qsort sorts any type. You give it the array, the count, the size of each, and how to compare. The comparison returns a negative number when a should come first, positive when b should, 0 when they're equal.

main.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct {5    char name[8];6    int score;7} Student;8 9// higher score first; equal scores by name10int by_score(const void *a, const void *b) {11    const Student *x = a, *y = b;12    if (x->score != y->score)13        return y->score - x->score;14    return x->name[0] - y->name[0];15}16 17int main(void) {18    Student s[] = {{"Lin", 88}, {"Ana", 95}, {"Bo", 88}, {"Cy", 72}};19    qsort(s, 4, sizeof(Student), by_score);20    for (int i = 0; i < 4; i++)21        printf("%-4s %d\n", s[i].name, s[i].score);22    return 0;23}
Output
Ana  95
Bo   88
Lin  88
Cy   72

Two traps: qsort is not guaranteed stable (two people with the same score may swap order), so if you want them by name, write it into the comparison, as by_score does; and comparing ints with a plain return x - y overflows for large values (say x = 2×10⁹, y = −2×10⁹). The safe form is return (x > y) - (x < y);.

Choose one

Comparing two ints with return x - y;: in which case does it go wrong?

Exercise 1

Sorting by two keys

Finish the comparison: younger first, and with equal ages the smaller id first. Compare with (x > y) - (x < y).

It should print
5 1 2 3 4
exercise1.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct {5    int id;6    int age;7} P;8 9int cmp(const void *a, const void *b) {10    const P *x = a, *y = b;11    // age first, then id12    return 0;13}14 15int main(void) {16    P p[] = {{3, 30}, {1, 25}, {4, 30}, {2, 25}, {5, 18}};17    qsort(p, 5, sizeof(P), cmp);18    for (int i = 0; i < 5; i++)19        printf("%d ", p[i].id);20    printf("\n");21    return 0;22}
Output
Press Run or Ctrl+Enter
Exercise 2

Any duplicates?

Sort with qsort first; duplicates then sit side by side, so compare neighbours only. Print 1 (yes) or 0 (no).

It should print
0 1
exercise2.c
1#include <stdio.h>2#include <stdlib.h>3 4int cmp(const void *a, const void *b) {5    int x = *(const int *)a, y = *(const int *)b;6    return (x > y) - (x < y);7}8 9int has_dup(int a[], int n) {10    // qsort it, then see whether two neighbours are equal11    return 0;12}13 14int main(void) {15    int a[] = {8, 3, 5, 1, 9}, b[] = {4, 7, 2, 7, 1};16    printf("%d %d\n", has_dup(a, 5), has_dup(b, 5));17    return 0;18}
Output
Press Run or Ctrl+Enter

The k-th smallest: no full sort

Sorting to find the k-th smallest is O(n log n). Quickselect borrows quicksort's partition: after one partition the pivot is at index m. If m is k, that's it; if k is to the left, look only on the left, otherwise only on the right. One side each time: O(n) on average.

acomparisons 0 · swaps 072943850123456

The 3rd smallest (index 2) in 7 2 9 4 3 8 5: one partition puts the pivot 5 at index 3; 2 < 3, so the search goes on only in 2 4 3 on the left
main.c
1#include <stdio.h>2 3void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }4 5int partition(int a[], int lo, int hi) {6    int p = a[hi], i = lo;7    for (int j = lo; j < hi; j++)8        if (a[j] < p) swap(&a[i++], &a[j]);9    swap(&a[i], &a[hi]);10    return i;11}12 13// the k-th smallest (k counted from 0)14int select_k(int a[], int lo, int hi, int k) {15    while (1) {16        int m = partition(a, lo, hi);17        if (m == k) return a[m];18        if (k < m) hi = m - 1;19        else lo = m + 1;20    }21}22 23int main(void) {24    int a[] = {7, 2, 9, 4, 3, 8, 5};25    printf("3rd smallest: %d\n", select_k(a, 0, 6, 2));26    return 0;27}
Output
3rd smallest: 4

"Top k", "median" and "k-th largest" are all this pattern. The other common interview answer is a heap of size k, O(n log k), covered in chapter 4 (heap sort).

Choose one

Quickselect is looking for the smallest number (index 0) in 6 1 8 3 5. After one partition around 5, the array is 1 3 5 6 8, with 5 at index 2. Where does it look next?

Exercise 3

Quickselect

partition is given. Finish select_k: after partitioning the pivot is at m; return it if m equals k, otherwise go on in one side only.

It should print
3 7
exercise3.c
1#include <stdio.h>2 3void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; }4 5int partition(int a[], int lo, int hi) {6    int p = a[hi], i = lo;7    for (int j = lo; j < hi; j++)8        if (a[j] < p) swap(&a[i++], &a[j]);9    swap(&a[i], &a[hi]);10    return i;11}12 13int select_k(int a[], int lo, int hi, int k) {14    // loop: m = partition; m == k returns a[m]; k < m goes left, otherwise right15    return -1;16}17 18int main(void) {19    int a[] = {12, 3, 5, 7, 4, 19, 26};20    int b[] = {12, 3, 5, 7, 4, 19, 26};21    printf("%d %d\n", select_k(a, 0, 6, 0), select_k(b, 0, 6, 3));22    return 0;23}
Output
Press Run or Ctrl+Enter

What one pass leaves

The most common long exam question: given an array, what does it look like after one pass (or two) of some sort? Each sort's "pass" does something different; know them and you can write the answer straight down:

SortWhat one pass does5 2 8 1 9 3 after one pass
Bubbleneighbours compared, the largest to the end2 5 1 8 3 9
Selectionthe smallest swapped to the front1 2 8 5 9 3
Insertionthe first two sorted2 5 8 1 9 3
Quick (last as pivot)one partition2 1 3 5 9 8
Choose one

What does 6 3 8 2 5 look like after one pass of bubble sort (compare neighbours, move the bigger one back)?

Summary

Take-away

Four sorting patterns

  • Unstable: selection, Shell, quick, heap; O(n log n) even at worst: merge, heap
  • Real code uses qsort; compare with (x > y) - (x < y), no overflow; not stable
  • k-th smallest: quickselect, one side after each partition, O(n) on average
  • After one pass: write it from that sort's own idea of "a pass"
1int cmp(const void *a, const void *b) {2    int x = *(const int *)a, y = *(const int *)b;3    return (x > y) - (x < y);4}5qsort(a, n, sizeof(int), cmp);

Chapter 7 quick check

5 questions: what one pass leaves, how many moves and comparisons, how many recursive calls, and stability. Work out what each prints before you pick.

Guess the outputA wrong guess is fine

One pass of bubble sort on 4 3 2 1. What does it print?

1#include <stdio.h>2 3int main(void) {4    int a[] = {4, 3, 2, 1};5    for (int j = 0; j < 3; j++)6        if (a[j] > a[j + 1]) {7            int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;8        }9    for (int i = 0; i < 4; i++)10        printf("%d ", a[i]);11    printf("\n");12    return 0;13}
Guess the outputA wrong guess is fine

Insertion sort on the fully reversed 5 4 3 2 1: how many moves?

1#include <stdio.h>2 3int main(void) {4    int a[] = {5, 4, 3, 2, 1};5    int n = 5, moves = 0;6    for (int i = 1; i < n; i++) {7        int key = a[i], j = i - 1;8        while (j >= 0 && a[j] > key) {9            a[j + 1] = a[j];10            j--;11            moves++;12        }13        a[j + 1] = key;14    }15    printf("%d\n", moves);16    return 0;17}
Guess the outputA wrong guess is fine

Quicksort with the last element as pivot, on the already sorted 0 to 9: how many comparisons?

1#include <stdio.h>2 3long long cmps = 0;4 5void qs(int a[], int lo, int hi) {6    if (lo >= hi) return;7    int p = a[hi], i = lo;8    for (int j = lo; j < hi; j++) {9        cmps++;10        if (a[j] < p) { int t = a[i]; a[i] = a[j]; a[j] = t; i++; }11    }12    int t = a[i]; a[i] = a[hi]; a[hi] = t;13    qs(a, lo, i - 1);14    qs(a, i + 1, hi);15}16 17int main(void) {18    int a[10];19    for (int i = 0; i < 10; i++) a[i] = i;20    qs(a, 0, 9);21    printf("%lld\n", cmps);22    return 0;23}
Guess the outputA wrong guess is fine

Merge sort on 6 numbers: how many calls to merge_sort?

1#include <stdio.h>2 3int calls = 0;4 5void ms(int lo, int hi) {6    calls++;7    if (lo >= hi) return;8    int mid = (lo + hi) / 2;9    ms(lo, mid);10    ms(mid + 1, hi);11}12 13int main(void) {14    ms(0, 5);15    printf("%d\n", calls);16    return 0;17}
Guess the outputA wrong guess is fine

Selection sort by key on (2,a) (2,b) (1,c). In what order are the tags printed?

1#include <stdio.h>2 3typedef struct { int key; char tag; } R;4 5int main(void) {6    R r[] = {{2, 'a'}, {2, 'b'}, {1, 'c'}};7    int n = 3;8    for (int i = 0; i < n - 1; i++) {9        int min = i;10        for (int j = i + 1; j < n; j++)11            if (r[j].key < r[min].key) min = j;12        R t = r[i]; r[i] = r[min]; r[min] = t;13    }14    for (int i = 0; i < n; i++)15        printf("%c", r[i].tag);16    printf("\n");17    return 0;18}