Example 1 — Count work for three simple sorts
The input is 5, 1, 4, 2, 8.
#include <stdio.h>
#include <string.h>
int main(void) {
int src[] = {5, 1, 4, 2, 8};
int a[5], n = 5;
memcpy(a, src, sizeof a);
int cmps = 0, swaps = 0;
for (int i = 0; i < n - 1; i++) {
int swapped = 0;
for (int j = 0; j < n - 1 - i; j++) {
cmps++;
if (a[j] > a[j + 1]) {
int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
swaps++;
swapped = 1;
}
}
if (!swapped) break;
}
printf("bubble: %d comparisons, %d swaps\n", cmps, swaps);
memcpy(a, src, sizeof a);
cmps = 0; swaps = 0;
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
cmps++;
if (a[j] < a[min]) min = j;
}
if (min != i) {
int t = a[i]; a[i] = a[min]; a[min] = t;
swaps++;
}
}
printf("selection: %d comparisons, %d swaps\n", cmps, swaps);
memcpy(a, src, sizeof a);
cmps = 0; int shifts = 0;
for (int i = 1; i < n; i++) {
int key = a[i], j = i - 1;
while (j >= 0) {
cmps++;
if (a[j] > key) { a[j + 1] = a[j]; shifts++; j--; }
else break;
}
a[j + 1] = key;
}
printf("insertion: %d comparisons, %d shifts\n", cmps, shifts);
return 0;
} How It Works
- Selection sort always makes 4 + 3 + 2 + 1 = 10 comparisons but few swaps.
- Bubble sort stops after three passes (4 + 3 + 2 = 9 comparisons) because the last pass swaps nothing.
- Insertion sort uses the fewest comparisons here because the data is almost ordered.
