<style> .reveal-up, .reveal-left, .reveal-right, .reveal-stagger > * { opacity: 1 !important; transform: none !important; } </style>
  1. Learn
  2. DSA
  3. Searching and sorting
All lessons in this course

Lesson 14 of 50 15 minIntermediate

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.

Sorting means putting items in order. It makes searching fast (binary search), makes duplicates sit next to each other, and makes reports readable. The three simple sorts below are not what you use for a million items, but they teach the basic moves every sorting algorithm uses, and one of them is still used inside professional libraries.

Interactive

Three simple sorts

Pick an algorithm and an input, then step or play. Watch the counters: try every algorithm on the nearly sorted input.
compared current minimum / value being inserted sorted part

Input
Comparisons 0 · Swaps 0
Bubble sort: compare neighbours and swap them if they are in the wrong order. The biggest value bubbles to the end each pass.

Bubble sort

Walk through the array comparing neighbours and swap them if they are in the wrong order. After the first pass the largest value has “bubbled” to the end. Repeat on the rest. If a whole pass makes no swaps, the array is sorted and you can stop early.

BubbleSort.cs
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

Find the smallest value in the unsorted part and swap it to the front of that part. Repeat. It always does the same number of comparisons, but at most n − 1 swaps, which helps when writing to memory is expensive.

SelectionSort.cs
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

Keep the left part sorted. Take the next value (the “key”), and shift bigger values one place right until you find the key’s spot, exactly like sorting playing cards in your hand.

InsertionSort.cs
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));
Output
1 2 3 4 5 7 8 9

Comparing them

BubbleSelectionInsertion
Best caseO(n) (sorted, early exit)O(n²)O(n) (sorted)
Average / worstO(n²)O(n²)O(n²)
Swaps / writesManyAt most n − 1 swapsMany shifts
Extra memoryO(1)O(1)O(1)
Stable?YesNoYes
Good forTeachingFew writesSmall or nearly sorted data

A sort is stable if items with equal keys keep their original order. Sort a beam schedule by profile with a stable sort and the beams within each profile stay in the order they were. Selection sort is not stable because its long-distance swap can jump an item over an equal one. Stability gets its own section in the .NET sorting lesson.

Why insertion sort still matters

Insertion sort does very little work when the data is nearly sorted: each item only shifts a short distance, so it approaches O(n). For tiny arrays it also beats the clever algorithms, because it has almost no overhead. That is why .NET’s Array.Sort switches to insertion sort for pieces of 16 elements or fewer.

Quick check

Which simple sort makes at most n − 1 swaps?

Quick check

A list of 10,000 readings is already sorted except for two neighbouring values. Which simple sort finishes fastest?

Practice

Change insertion sort to sort beam lengths (double[]) in descending order: { 4.5, 6.0, 3.0, 7.2, 6.0 } → 7.2, 6, 6, 4.5, 3.

Show a hint

Only the comparison in the while loop changes: shift values that are smaller than the key.

Show the solution
Solution.cs
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));
Output
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.
0 of 50 lessons completed