Data Structures & Algorithms / Module 4: Searching and sorting

Topic 4.3

Bubble, selection and insertion sort

Three ways to sort by comparing pairs: simple, but n².

9 min · beginner

Watch: the two lit blocks are being compared. Count the comparisons, then try the nearly sorted data.

012345528193
  • moving now
  • being checked
  • finished / the result
Step 1 of 16

Bubble sort: compare two neighbours and swap them if they are in the wrong order. The largest 'bubbles' to the right.

All three compare numbers in pairs and need about n² steps in the worst case. Try the nearly sorted data: insertion sort is much faster there.
data:

Three ways people sort by hand

  • Bubble sort: walk left to right, swapping any two neighbours that are in the wrong order. After one pass, the largest number is sure to be at the right end. Repeat for the rest.
  • Selection sort: find the smallest and put it first. Find the smallest of what's left and put it second. And so on. Like picking players one at a time, shortest first.
  • Insertion sort: take the next number and slide it left until it finds its place in the sorted part. Like arranging playing cards in your hand.
Code, for programmersInsertion sort
function insertionSort(a) {
  for (let i = 1; i < a.length; i++) {
    let j = i;
    // slide a[j] left while the number before it is bigger
    while (j > 0 && a[j - 1] > a[j]) {
      [a[j - 1], a[j]] = [a[j], a[j - 1]];
      j--;
    }
  }
  return a;
}

Why n²

Selection sort compares the first number with n − 1 others, the second with n − 2, and so on. That adds up to about n²/2. For 1,000 numbers that is around 500,000 comparisons; for a million numbers, 500 billion. That is why programming languages don't use these for their built-in sort().

So why learn them

  • For small lists (a dozen or so numbers) insertion sort is actually the fastest, because the code is simple and needs no extra memory. JavaScript's built-in sort (TimSort in V8) uses insertion sort for small chunks.
  • Nearly sorted data (say a list that just had one item added) takes insertion sort about n steps.
  • All three are the easiest way to practise reading nested loops and working out their cost.

Quiz

  1. After one full pass of bubble sort, what is certainly true?

  2. The data is nearly sorted: just two neighbours are swapped. Which is fastest?

  3. What does [10, 9, 1].sort() give in JavaScript?

0 of 3 answered.