Sorting
Putting things in order is one of the jobs computers do most. There are many ways to do it, and some are much faster than others. Here, every method gets the same messy row of bars, and can only do two things: compare two bars, and move them.
- To compare two items is to ask which one is bigger. We count comparisons to measure how much work a method does.
- To swap is to make two items trade places.
- To merge is to combine two sorted piles into one sorted pile.
The race: every method on this same list
- Try each method on an already sorted list. Which ones notice it's sorted and finish fast? Which keep working anyway?
- With 8, 16, 32 and 64 shuffled bars, how do the comparisons for insertion sort grow each time the list doubles? How about merge sort?
- Is there a starting list where insertion sort beats merge sort?
Curator's answers
- Insertion sort and bubble sort each make one quick pass and stop. Selection sort still hunts for the smallest bar every time, and merge sort still splits and merges everything.
- Insertion sort's work roughly quadruples when the list doubles: twice as many bars, and each one has about twice as far to slide. Merge sort's work only a bit more than doubles. For a million items that's the difference between several minutes and a fraction of a second. For a billion, it's years against seconds.
- Yes: an already sorted or nearly sorted list. Real-world sorting programs (like the ones in Python and Java) mix the two: they use insertion sort on short runs and merge the runs together.
From the archive
Insertion sort is how most people sort a hand of playing cards: pick up each new card and slide it left into its place. Merge sort was written by John von Neumann in 1945, for one of the first computers that kept its own program in memory. Even before computers, punched-card sorting machines from Herman Hollerith's company were sorting cards in the early 1900s, one column of holes at a time. Timsort, a careful mix of insertion and merge sort written by Tim Peters in 2002, is behind the sorting built into Python and Java.