StringMash.com

Sorting algorithms

Six sorts on your own list, animated, and compared by how much work each does.

Conversion

Sorting only goes one way: a sorted list doesn't remember the order it started in.

23 characters
Updates as you type
Pick a sort in To; the animation is below

Show the steps
  1. End of pass 1: 10 has bubbled up to its final place. The list is now 2, 7, 4, 9, 1, 8, 3, 10.
  2. End of pass 2: 9 has bubbled up to its final place. The list is now 2, 4, 7, 1, 8, 3, 9, 10.
  3. End of pass 3: 8 has bubbled up to its final place. The list is now 2, 4, 1, 7, 3, 8, 9, 10.
  4. End of pass 4: 7 has bubbled up to its final place. The list is now 2, 1, 4, 3, 7, 8, 9, 10.
  5. End of pass 5: 4 has bubbled up to its final place. The list is now 1, 2, 3, 4, 7, 8, 9, 10.
  6. Pass 6 made no swaps, so every item is already in order. Done.

Watch it sort

  • Being compared
  • Just moved
  • In its final place
  • Not being worked on

Type a list above to see it sorted step by step.

Printable chart

Using the comparison

Type a list, then choose a sort in the To box. The animation below plays that algorithm on your list, and switching the sort switches the animation, so you can watch the same list sorted six different ways. Each sort also has its own page, with more on how it works.

MEASURED ON THIS SITE'S OWN SORTS

Comparisons for ten numbers

AlgorithmShuffledAlready sortedReversedKeeps equal items in order
Bubble sort39945Yes
Selection sort454545No
Insertion sort31945Yes
Merge sort241915Yes
Quick sort234545No
Heap sort374135No

Reading the table

Each number is how many comparisons that sort makes on ten numbers: shuffled, already in order, and in reverse. They're measured by running the same code the animations use, so they're exactly what you'd count by stepping through.

Bubble sort and insertion sort shine on a list that's already sorted, finishing in nine comparisons. Selection sort makes 45 whatever it's given. Quick sort, picking the last item as its pivot, is fastest on the shuffled list and slowest on the ordered ones. Merge sort and heap sort stay steady.

The last column is whether two equal items stay in the order they started in, tested on several lists with repeats.

Each sort on its own page

8 converters in 2 groups

Questions

Which sorting algorithm is fastest?

For long lists, merge sort, heap sort and a well-built quick sort, which all grow with n log n rather than n². Quick sort is often quickest in practice. For short or nearly sorted lists, insertion sort can beat all of them.

What does O(n log n) mean?

That the work grows a little faster than the length of the list. Doubling the list slightly more than doubles the work. O(n²) means doubling the list quadruples it.

Why does the animation only go up to 3 steps a second?

Each step recolours a bar or two, and three changes a second is the limit the web's accessibility guidelines set for anything that flashes. Step forward goes as fast as you can click.