Bubble, selection & insertion sort
O(n²) sorts — and why insertion sort is still used inside fast ones.
Before you start
Sorting a list of values is one of the most-solved problems in computing. The three algorithms in this lesson are the simplest ones — none of them are what a professional library actually uses for large data, but they are the ones you learn first because their logic is easy to hold in your head.
**Bubble sort** repeatedly swaps adjacent out-of-order pairs. **Selection sort** repeatedly finds the minimum and puts it up front. **Insertion sort** takes each element and slides it back into its correct place among the already-sorted ones.
This lesson watches each one sort the same array of 5 values. All three are O(n²), but they move elements in very different ways — and insertion sort has one trick that makes real sort libraries still use it inside.
Unsorted
[5, 3, 8, 1, 4]. Three ways to sort them, same result.
Step 1 of 6. Five unsorted values. The array is [5, 3, 8, 1, 4]. All three sorts will produce [1, 3, 4, 5, 8], but they move elements in different ways. All three are O(n²) in the worst case, which means they compare roughly 25 pairs for 5 elements.
Step 01 / 06
Five unsorted values
The array is [5, 3, 8, 1, 4]. All three sorts will produce [1, 3, 4, 5, 8], but they move elements in different ways.
All three are O(n²) in the worst case, which means they compare roughly 25 pairs for 5 elements.
// Bubble sort: swap adjacent pairs, repeatvoid bubble_sort(int arr[], int n) { for (int i = 0; i < n - 1; i++) for (int j = 0; j < n - 1 - i; j++) if (arr[j] > arr[j+1]) swap(&arr[j], &arr[j+1]);}// Selection sort: find min, swap to frontvoid selection_sort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { int min_idx = i; for (int j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; swap(&arr[i], &arr[min_idx]); }}// Insertion sort: slide each element into placevoid insertion_sort(int arr[], int n) { for (int i = 1; i < n; i++) { int key = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > key) { arr[j+1] = arr[j]; j--; } arr[j+1] = key; }}