← Computing hubSimulationsComputing quizzes

Sorting algorithm lab

Simulated lab, original BrainJoy code

Watch a sorting algorithm work one step at a time. Orange bars are being compared, red bars were just swapped or moved, blue is the value being inserted, green is in its final place. The counters show how much work the algorithm has done.

Pick an algorithm and press Step or Play.
Comparisons: 0
Swaps or moves: 0
Not sorted yet

What to try

  1. Run bubble sort on a reversed array and note the comparisons. Then run it on a nearly sorted array. Which needs less work?
  2. Run selection sort on both. Does the start order change its comparison count?
  3. Run insertion sort on a nearly sorted array. Why does it finish with so few moves?

What the counts show

AlgorithmIdeaComparisons for n items
Bubble sortSwap neighbours that are out of order. Repeat passes until a pass makes no swap.Up to n(n-1)/2. Fewer if the list is nearly sorted, because it stops early.
Selection sortFind the smallest unsorted value and put it next.Always n(n-1)/2, whatever the start order.
Insertion sortTake the next value and slide it back into the sorted part.As few as n-1 when nearly sorted, up to n(n-1)/2 when reversed.

This is a simulation for learning the idea. It uses small lists and counts only comparisons and swaps or moves. Real programs also use faster methods such as merge sort, which are not shown here. Nothing is saved or sent anywhere.