Bubble, selection and insertion sort
Three simple O(n²) sorting algorithms, how they differ in comparisons, swaps and stability, and why insertion sort is still used inside .NET today.
Bubble sort
static void BubbleSort(int[] a){ for (int pass = 0; pass < a.Length - 1; pass++) { bool swapped = false; for (int j = 0; j < a.Length - 1 - pass; j++) // the last 'pass' items are done { if (a[j] > a[j + 1]) { (a[j], a[j + 1]) = (a[j + 1], a[j]); swapped = true; } } if (!swapped) break; // already sorted }}Selection sort
static void SelectionSort(int[] a){ for (int i = 0; i < a.Length - 1; i++) { int min = i; for (int j = i + 1; j < a.Length; j++) if (a[j] < a[min]) min = j; if (min != i) (a[i], a[min]) = (a[min], a[i]); }}Insertion sort
static void InsertionSort(int[] a){ for (int i = 1; i < a.Length; i++) { int key = a[i]; int j = i - 1; while (j >= 0 && a[j] > key) // shift bigger values right { a[j + 1] = a[j]; j--; } a[j + 1] = key; // drop the key into the gap }} int[] data = { 5, 2, 8, 1, 9, 3, 7, 4 };InsertionSort(data);Console.WriteLine(string.Join(" ", data));1 2 3 4 5 7 8 9
Comparing them
| Bubble | Selection | Insertion | |
|---|---|---|---|
O(n) (sorted, early exit) | O(n²) | O(n) (sorted) | |
O(n²) | O(n²) | O(n²) | |
O(1) | O(1) | O(1) | |
Why insertion sort still matters
Array.Sort switches to insertion sort for pieces of 16 elements or fewer.
double[]) in descending order: { 4.5, 6.0, 3.0, 7.2, 6.0 } → 7.2, 6, 6, 4.5, 3.
Show a hint
Show the solution
static void InsertionSortDescending(double[] a){ for (int i = 1; i < a.Length; i++) { double key = a[i]; int j = i - 1; while (j >= 0 && a[j] < key) // was: a[j] > key { a[j + 1] = a[j]; j--; } a[j + 1] = key; }} double[] lengths = { 4.5, 6.0, 3.0, 7.2, 6.0 };InsertionSortDescending(lengths);Console.WriteLine(string.Join(", ", lengths));7.2, 6, 6, 4.5, 3
Remember
Bubble, selection and insertion sort are O(n²) in the average and worst case and need O(1) extra memory. Insertion sort is O(n) on nearly sorted data and is used for small pieces inside Array.Sort.Selection sort minimises swaps but is not stable. A stable sort keeps equal items in their original order.