Chapter 4 · Simulation

Sorting Algorithm Visualizer

← Chapter 4

being compared swap / write minIdx in its final place

Sorting visualizer

Goal: Watch which items the sorting algorithms from the slides compare at each step and how they move; compare the numbers of comparisons and swaps across algorithms and starting orders.

How to use it

  1. Choose the algorithm, the array size (5–40) and the starting order; New array generates new random values.
  2. Step ▶ advances one step, ◀ Back goes back one step, Play runs automatically to the end. In the pseudocode on the right the line running in that step is highlighted.
  3. While Predict is ticked, the run stops at every comparison: predict whether the condition will be True or False; your score is kept at the bottom right.

What to look for

AlgorithmComparisonsHint
Selectionalways n(n−1)/2at most n−1 swaps
Bubblen−1 on a sorted arraystops after a pass with no swaps
Insertionn−1 on a sorted arrayworst case on a reversed array
Merge≈ n log₂ nhelper array: extra memory O(n)

In insertion sort the second counter shows the number of shifts (arr[j+1] = arr[j]); in merge sort it shows the number of writes from the temporary array back into the array.

Related slides: Chapter 4.1 · Algorithms.