Visual sorting: bubble, selection, insertion and merge sort step by step

Computer ScienceAlgorithms & Problem SolvingAges 13–14

Loading…

Use with my class ✨ Customize with AI Report a problem

A sequence of numbers is drawn as bars; choose bubble sort, selection sort, insertion sort or merge sort, then press Step or Run. Each step highlights the pair being compared, the pair being swapped and the part already sorted, while counting comparisons and swaps; the matching line of pseudocode is highlighted too. Merge sort splits the bars into halves level by level and merges them back, and a table and graph compare the comparison counts of all four algorithms (n log n against n²). Students can drag a bar to change its value before running.

Lesson: Sorting algorithms (bubble, selection, insertion, merge), nested loops and divide and conquer

What it shows

Bubble, selection and insertion sort rearrange a list with nested loops, so for n elements they need about n²/2 comparisons in the worst case. Selection sort makes at most n − 1 swaps, bubble sort can stop after a pass with no swaps, and insertion sort is very fast on nearly sorted data. Merge sort uses divide and conquer: it splits the list in half again and again until single elements remain, then merges sorted halves back together. Each of its about log₂n levels costs at most n comparisons, so it needs roughly n·log₂n comparisons in any order, far fewer than n²/2 when n is large.

How to use

Start with about 8 elements and press Step, asking students to predict each highlighted comparison while following the matching pseudocode line. Press Run and record the comparisons and swaps, then switch Algorithm and repeat with the Descending and Nearly sorted options. Choose Merge sort to watch the bars split level by level and merge back; the table and graph below put the same sequence through all four algorithms. Students can also drag a bar before running.

Parameters you can change

  • Number of elements 4–30
  • Algorithm Bubble sort, Selection sort, Insertion sort, Merge sort
  • Initial sequence Random, Descending (worst case), Nearly sorted
  • Run speed 1–20 steps/s
  • Show comparison of all four algorithms

Questions to explore

  1. After the first pass of bubble sort, which element is guaranteed to be in its final place?
  2. Which algorithm makes the fewest swaps on a descending sequence, and why?
  3. Why does insertion sort finish so quickly on a nearly sorted sequence?