CleverSphere

Bubble sort, insertion sort and selection sort

The three simple methods take quadratic time but are exam classics. You are often asked for the state after a few passes.

Rules

  • Bubble sort: swap neighbours, the largest moves to the end
  • Selection sort: find the minimum, swap once
  • Insertion sort: insert the next element into the sorted part

Your turn

Three problems on this topic. Separate lists with commas.

  1. 1 · Simple sorts
  2. 2
  3. 3

Selection sort sorts in ascending order. What does the array look like after 2 passes?

[42, 44, 21, 26, 31, 9]

Array (comma-separated)

Worked example

Bubble sort sorts in ascending order. What does the array look like after 3 passes?

[58, 36, 22, 56, 25, 8, 60]

Worked solution

  1. 1After pass 1: [36, 22, 56, 25, 8, 58, 60]
  2. 2After pass 2: [22, 36, 25, 8, 56, 58, 60]
  3. 3After pass 3: [22, 25, 8, 36, 56, 58, 60]

Typical mistake: Bubble sort moves the largest element to the end each pass, selection sort swaps only once per pass.

Common questions

Which one is fastest?

All are O(n²); insertion sort is nearly linear on almost sorted data.

Related

More topics