Selection sort in C, visualized step by step
Each pass finds the smallest value in the unsorted part and swaps it with the first value of that part. After n − 1 passes the list is sorted from the front.
selection_sort.c
#include <stdio.h>
int main(void) {
int a[] = {29, 10, 14, 37, 13};
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;
int t = a[i];
a[i] = a[min];
a[min] = t;
}
for (int i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
return 0;
}
How Selection sort works
- Assume the value at position i is the smallest.
- Scan the rest; whenever a smaller one turns up, remember its index.
- After the scan, swap the smallest into position i.
- Move i one place right and repeat until the end.
What to watch
The smallest indexIt jumps to each smaller value during the scan; there is one swap per pass.
Left of iThe bars left of i are sorted and never move again.
FAQ
What is the time complexity of selection sort?
Always O(n²): every pass scans the whole remaining part, n(n − 1)/2 comparisons in total. It does at most n − 1 swaps, though.
Is selection sort stable?
No. Swapping the smallest to the front can move a value behind an equal one, e.g. [5, 5, 1].
Selection sort vs bubble sort?
The same number of comparisons, but selection sort swaps once per pass while bubble sort may swap many times. Bubble sort is stable and can stop early; selection sort is neither.