Selection sort divides the array into a sorted prefix and an unsorted rest. Each step selects the minimum of the rest and swaps it into the next position. It always makes O(n^2) comparisons but only at most n - 1 swaps, which helps when writes are expensive. It is not stable in the usual swap form.
Remember
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++) if (a[j] < a[min]) min = j;
if (min != i) swap(a[i], a[min]);
}
Reference
Cheat Sheet
Keep these facts handy while you work with Selection Sort in C.
Topic
Detail
Comparisons
n(n-1)/2 always
Swaps
At most n - 1
Space
O(1)
Stable
No (swap form)
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Insertion Sort.
Example 1 — Trace each selection step
Sort 64, 25, 12, 22, 11.
C
#include <stdio.h>
int main(void) {
int a[] = {64, 25, 12, 22, 11};
int n = 5;
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; }
printf("step %d:", i + 1);
for (int k = 0; k < n; k++) printf(" %d", a[k]);
printf("\n");
}
return 0;
}