edubun
English
1 / 19

3 / 7 · Basic

Sorting 1: bubble, selection and insertion sort

Selection sort makes exactly 45 comparisons on any list of 10 values, whether the list starts shuffled or already in order.

Jump to the 11 practice questions

You will learn

  • Follow bubble, selection and insertion sort step by step
  • Predict swaps from inversions

Before this: Searching: linear and binary search

1Explain

Putting things in order

This unit covers three simple methods. All three work by comparing two values at a time and moving values around inside the same list. They are short to write and easy to follow, and all three slow down sharply on long lists. Watching why they slow down is the best preparation for the faster methods in the next unit. Throughout, we count two things: comparisons (asking "is this value bigger than that one?") and swaps (exchanging two values).

2Explore

Bubble sort

Bubble sort walks along the list comparing each pair of neighbours. When the left one is bigger, it swaps them. After one full pass, the largest value has been carried step by step to the far right, like a bubble rising, and it never needs to move again. The next pass can stop one place earlier. A common improvement is to watch for a pass with no swaps at all: that means everything is already in order, so the sort can stop early.

Yellow bars are being compared; orange bars have just swapped; green bars are in their final place.

01234

Start: compare and swap until the list is in order.

Comparisons 0Swaps 0

3Problem

Comparisons in bubble sort

How many comparisons does bubble sort (with the early stop) make on [5, 1, 4, 2, 8]?

Hint

Passes of 4, 3 and 2 comparisons; the third pass swaps nothing.

Solution

Answer: 9

Each pass compares the neighbouring pairs that are still unsorted: 4, 3 and 2 comparisons. The third pass makes no swap, so it stops.

4Problem

After the first pass

After the first pass of bubble sort, which value is certainly in its final place?

Hint

Follow the biggest value through the first pass.

Solution

Answer: The largest, at the end

The largest value wins every comparison it is in, so it is carried all the way to the end.

5Explore

Selection sort

Selection sort works the way many people sort a hand of cards. Scan the whole list for the smallest value and swap it into the first position. Then scan the rest for the smallest remaining value and swap it into the second position, and so on. On [5, 1, 4, 2, 8] the first scan finds 1 and swaps it with 5. The second finds 2 and swaps it with 5.

Blue marks the smallest value found so far in this scan. One swap at the end of the scan, if needed.

01234

Start: compare and swap until the list is in order.

Comparisons 0Swaps 0

6Problem

Selection sort on 10 values

How many comparisons does selection sort make on any list of 10 values?

Hint

9 + 8 + … + 1.

Solution

Answer: 45

Selection sort scans all the values still unsorted, so it compares 9, then 8, down to 1, whatever the starting order: 9 + 8 + … + 1 = 10 × 9 / 2 = 45.

7Problem

Fewest swaps

Which method does the fewest swaps on [5, 1, 4, 2, 8]?

Hint

Count the swaps on the three counters you have seen.

Solution

Answer: Selection sort

Selection sort makes at most one swap per pass, so it makes 2 swaps here; bubble and insertion sort swap neighbours one at a time and make 4 each.

8Explore

Insertion sort

Insertion sort keeps the left part of the list sorted and grows it one value at a time. It takes the next value and moves it left, swapping with its neighbour, until the neighbour is not bigger. Then that value is in place among the sorted ones. On a list that is already nearly in order, each new value moves only a step or two, so insertion sort is very quick there.

The blue bar is the value being inserted. It moves left, one swap at a time, until its left neighbour is not bigger.

01234

Start: compare and swap until the list is in order.

Comparisons 0Swaps 0

9Problem

Insertion sort on [3, 1, 2]

Put the list [3, 1, 2] in the order it passes through during insertion sort.

  1. [3, 1, 2]
  2. [1, 2, 3]
  3. [1, 3, 2]
Hint

First 1 slides past 3, then 2 slides past 3.

Solution

Answer:

  1. [3, 1, 2]
  2. [1, 3, 2]
  3. [1, 2, 3]

1 slides left past 3, then 2 slides left past 3 and stops after 1.

10Explain

Counting the swaps: inversions

There is a neat way to predict how many swaps bubble sort and insertion sort need. Count the inversions: pairs of values that are in the wrong order relative to each other. In [5, 1, 4, 2, 8] the inversions are (5, 1), (5, 4), (5, 2) and (4, 2), four in all. Each swap of two neighbours that are out of order fixes exactly one inversion and creates none, so both methods make exactly 4 swaps.

MethodExampleSorted (5 values)Reversed (4 values)
Bubble sort9 / 44 / 06 / 6
Selection sort10 / 210 / 06 / 2
Insertion sort7 / 44 / 06 / 6

Each cell gives comparisons / swaps. Bubble sort here stops after a pass with no swap.

11Problem

Inversions in [3, 1, 2]

How many inversions does [3, 1, 2] have?

Hint

Check the pairs (3, 1), (3, 2) and (1, 2).

Solution

Answer: 2

An inversion is a pair of values in the wrong order. (3, 1) and (3, 2) are out of order; (1, 2) is fine.

12Problem

A reversed list

How many swaps does insertion sort make on [4, 3, 2, 1]?

Hint

In [4, 3, 2, 1] every pair is out of order.

Solution

Answer: 6

A reversed list of 4 values has 4 × 3 / 2 = 6 inversions, and each swap fixes one.

13Explore

Nearly sorted

Only 3 and 4 are out of order. Insertion sort needs 6 comparisons and one swap here.

012345

Start: compare and swap until the list is in order.

Comparisons 0Swaps 0

14Problem

Best for nearly sorted

Which method is the best choice for a list that is nearly sorted already?

Hint

Which counter stayed lowest on the last page?

Solution

Answer: Insertion sort

Each new value only moves a step or two, so insertion sort does close to n comparisons.

15Problem

Twice the list

A list of 1,000 values becomes 2,000 values. Roughly how does the worst-case work of insertion sort change?

Hint

The work grows like n²/2.

Solution

Answer: It goes up about four times

The work is about n²/2, and (2n)² = 4n².

16Practice

Complete bubble sort

Complete bubble sort so the program prints [1,2,4,5,8].

Expected output
[1,2,4,5,8]
Your code
const a = [5, 1, 4, 2, 8];
for (let pass = 0; pass < a.length - 1; pass++) {
  for (let j = 0; j < a.length - 1 - pass; j++) {
    // If a[j] is bigger than a[j + 1], swap them.
  }
}
console.log(a);
Hint

Swap with [a[j], a[j + 1]] = [a[j + 1], a[j]]. Two plain assignments lose one value.

A solution
const a = [5, 1, 4, 2, 8];
for (let pass = 0; pass < a.length - 1; pass++) {
  for (let j = 0; j < a.length - 1 - pass; j++) {
    if (a[j] > a[j + 1]) {
      [a[j], a[j + 1]] = [a[j + 1], a[j]];
    }
  }
}
console.log(a);

17Practice

Count the swaps

Count the swaps bubble sort makes on [5, 1, 4, 2, 8]. The program should print 4, the number of inversions.

Expected output
4
Your code
const a = [5, 1, 4, 2, 8];
let swaps = 0;
// Bubble sort a, adding 1 to swaps for every swap.
console.log(swaps);
Hint

Add 1 only inside the if, where the swap happens.

A solution
const a = [5, 1, 4, 2, 8];
let swaps = 0;
for (let pass = 0; pass < a.length - 1; pass++) {
  for (let j = 0; j < a.length - 1 - pass; j++) {
    if (a[j] > a[j + 1]) {
      [a[j], a[j + 1]] = [a[j + 1], a[j]];
      swaps++;
    }
  }
}
console.log(swaps);

18Explain

Common mistakes

Mistake
const a = [5, 1, 4, 2, 8];
for (let j = 0; j < a.length - 1; j++) {
  if (a[j] > a[j + 1]) [a[j], a[j + 1]] = [a[j + 1], a[j]];
}
console.log(a);
Output
[1,4,2,5,8]
Fixed
const a = [5, 1, 4, 2, 8];
for (let pass = 0; pass < a.length - 1; pass++) {
  for (let j = 0; j < a.length - 1 - pass; j++) {
    if (a[j] > a[j + 1]) [a[j], a[j + 1]] = [a[j + 1], a[j]];
  }
}
console.log(a);
Output
[1,2,4,5,8]

One pass only carries the largest value to the end. Bubble sort needs passes until nothing moves.

Mistake
const a = [10, 9, 100, 2];
a.sort();
console.log(a);
Output
[10,100,2,9]
Fixed
const a = [10, 9, 100, 2];
a.sort((x, y) => x - y);
console.log(a);
Output
[2,9,10,100]

Without a compare function JavaScript sorts numbers as text, so "100" comes before "2". Pass (x, y) => x - y.

19

Summary

  • Bubble sort swaps neighbours; each pass carries the largest value to the end.
  • Selection sort always makes n(n − 1)/2 comparisons and at most n − 1 swaps.
  • Insertion sort is fast on nearly sorted lists.
  • Bubble and insertion sort make one swap per inversion.
  • All three take about n² steps in the worst case.

Next unitSorting 2: merge sort and quicksort
Full text · The whole lesson as one text

Putting things in order

Sorting means rearranging a list so its values go from smallest to largest (or by name, date, price, any order you can compare). It is one of the most common jobs a computer does: the contacts on a phone, search results ranked by relevance, a spreadsheet column sorted by date. Sorting also makes other jobs easier. As the last unit showed, a sorted list can be searched with binary search, and duplicates in a sorted list sit next to each other.

This unit covers three simple methods. All three work by comparing two values at a time and moving values around inside the same list. They are short to write and easy to follow, and all three slow down sharply on long lists. Watching why they slow down is the best preparation for the faster methods in the next unit. Throughout, we count two things: comparisons (asking "is this value bigger than that one?") and swaps (exchanging two values).

Bubble sort: swap neighbours that are out of order

Bubble sort walks along the list comparing each pair of neighbours. When the left one is bigger, it swaps them. After one full pass, the largest value has been carried step by step to the far right, like a bubble rising, and it never needs to move again. The next pass can stop one place earlier. A common improvement is to watch for a pass with no swaps at all: that means everything is already in order, so the sort can stop early.

Follow it on the list [5, 1, 4, 2, 8]. The first pass compares 5 and 1 (swap), 5 and 4 (swap), 5 and 2 (swap), 5 and 8 (leave): the list is now [1, 4, 2, 5, 8] and 8 is in place. The second pass compares 1 and 4, 4 and 2 (swap), 4 and 5, giving [1, 2, 4, 5, 8]. The third pass compares 1 and 2, then 2 and 4, makes no swap and stops. Total: 4 + 3 + 2 = 9 comparisons and 4 swaps.

function bubbleSort(a) {
  for (let pass = 0; pass < a.length - 1; pass++) {
    let swapped = false;
    for (let j = 0; j < a.length - 1 - pass; j++) {
      if (a[j] > a[j + 1]) {
        [a[j], a[j + 1]] = [a[j + 1], a[j]];  // swap
        swapped = true;
      }
    }
    if (!swapped) break;  // already sorted
  }
  return a;
}

Selection sort: find the smallest, put it next

Selection sort works the way many people sort a hand of cards. Scan the whole list for the smallest value and swap it into the first position. Then scan the rest for the smallest remaining value and swap it into the second position, and so on. On [5, 1, 4, 2, 8] the first scan finds 1 and swaps it with 5. The second finds 2 and swaps it with 5. The last two scans find 4 and 5 already in place. That is only 2 swaps, but the scans still compare 4 + 3 + 2 + 1 = 10 times.

Selection sort never stops early. Even on a list that is already sorted, it still has to check every remaining value to be sure it has the smallest. For n values the comparisons always add up to (n − 1) + (n − 2) + … + 1 = n(n − 1)/2. For 10 values that is 45; for 100 values, 4,950; for 1,000 values, 499,500. Its strength is the small number of swaps: at most n − 1, which matters when moving a value is expensive.

Insertion sort: slide each new value into place

Insertion sort keeps the left part of the list sorted and grows it one value at a time. It takes the next value and moves it left, swapping with its neighbour, until the neighbour is not bigger. Then that value is in place among the sorted ones. On a list that is already nearly in order, each new value moves only a step or two, so insertion sort is very quick there. On [5, 1, 4, 2, 8] it makes 7 comparisons and 4 swaps.

The list [5, 1, 4, 2, 8]. Switch between the three methods and check the counts in this unit. Then choose Reversed or Already sorted to see best and worst cases.

Counting the swaps: inversions

There is a neat way to predict how many swaps bubble sort and insertion sort need. Count the inversions: pairs of values that are in the wrong order relative to each other. In [5, 1, 4, 2, 8] the inversions are (5, 1), (5, 4), (5, 2) and (4, 2), four in all. Each swap of two neighbours that are out of order fixes exactly one inversion and creates none, so both methods make exactly 4 swaps. A reversed list of n values has every pair inverted, n(n − 1)/2 inversions, which is the worst case.

MethodExampleSorted (5 values)Reversed (4 values)
Bubble sort9 / 44 / 06 / 6
Selection sort10 / 210 / 06 / 2
Insertion sort7 / 44 / 06 / 6

Each cell gives comparisons / swaps. The example list is [5, 1, 4, 2, 8]. Bubble sort here is the version that stops after a pass with no swap.

All three methods share the same weakness. In the worst case each one compares roughly every pair of values, about n²/2 comparisons. Double the list and the work goes up four times. Ten times the list means a hundred times the work. For a few dozen values that hardly matters; for a million it is hopeless, and the next unit shows how to do far better.

Key points
  • Bubble sort swaps neighbours; each pass carries the largest value to the end.
  • Selection sort always makes n(n − 1)/2 comparisons and at most n − 1 swaps.
  • Insertion sort is fast on nearly sorted lists.
  • Bubble and insertion sort make one swap per inversion.
  • All three take about n² steps in the worst case.

Practice questions from Sorting 1: bubble, selection and insertion sort on edubun

Embed this quiz

Free to embed. Please keep the credit line.

Sources for this course (11)
  • MIT OpenCourseWare 6.006 Introduction to Algorithms, Spring 2020 (Demaine, Ku, Solomon)
  • lecture notes 1 Introduction, 3 Sorting, 9 Breadth-First Search, 10 Depth-First Search (ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/pages/lecture-notes) and Fall 2011 lecture 13 BFS notes (ocw.mit.edu/courses/6-006-introduction-to-algorithms-fall-2011)
  • Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms (MIT Press)
  • with the CLRS-based Khan Academy algorithms unit by Thomas Cormen and Devin Balkcom of Dartmouth (khanacademy.org/computing/computer-science/algorithms: binary search, selection sort analysis, merge sort, quicksort overview and analysis)
  • MacTutor History of Mathematics, Al-Khwarizmi (mathshistory.st-andrews.ac.uk/Biographies/Al-Khwarizmi: word algorithm from the Latin title Algoritmi de numero Indorum)
  • D. E. Joyce, Euclid's Elements Book VII Propositions 1 and 2 (mathcs.clarku.edu/~djoyce/elements/bookVII)
  • Wolfram MathWorld, Merge Sort (mathworld.wolfram.com/MergeSort.html: proposed by John von Neumann in 1945, after Knuth 1998 p. 159)
  • Stanford CS "Tony Hoare: Quicksort" (cs.stanford.edu/people/eroberts/courses/soco/projects/2008-09/tony-hoare/quicksort.html: devised while a student at Moscow State University for Russian-English machine translation with a tape dictionary, programmed in Algol 60 and published 1961; the year 1959 from the Wikipedia Quicksort article and its cited sources)
  • Bodleian Libraries, Ada Lovelace (blogs.bodleian.ox.ac.uk/adalovelace: 1843 paper, Note G Bernoulli numbers)
  • Fourmilab text of Menabrea's Sketch with Lovelace's notes (fourmilab.ch/babbage/sketch.html)
  • Seven Bridges of Konigsberg (Euler 1736) and Tower of Hanoi (Edouard Lucas, 1883) checked against the Wikipedia articles and their cited sources.

Checked: 2026-10-17