How computers sort things
A computer sorts by comparing two items at a time. Sort a row by hand, watch three methods race on one list and see how the work grows with the length of the list.
Key takeaways
- A computer sorts by comparing two items at a time. A good method uses few comparisons.
- A swap of neighbours fixes one wrong pair at most, so the fewest such swaps is the number of inversions.
- Bubble sort and insertion sort can need about n times n minus 1, over 2 comparisons. Merge sort needs about n times the base 2 logarithm of n.
- Ten times as many items is about a hundred times the work for bubble sort, and only a little more than ten times for merge sort.
- No sort that only compares pairs can always beat the base 2 logarithm of n factorial. Merge sort comes close.
Sources
Some of these sites could not be opened while this page was written, so some facts were checked through search results that quote them. Merge sort credited to John von Neumann in 1945 with a fuller account in 1948 appeared in a reference source and several others. That a swap of neighbours removes exactly one inversion, so the fewest such swaps equals the inversions, that a list of n items has at most n times n minus 1, over 2 inversions, and that the average is n times n minus 1, over 4, appeared in lecture notes. That a comparison sort needs at least log base 2 of n factorial comparisons in the worst case, which is about n log n, appeared in several places, and merge sort meets the bound closely. The counts of comparisons on the page come from running plain versions of the three methods on seeded lists and may differ a little from other versions of the same methods, for instance a bubble sort that does not stop early. Counting sort and radix sort are mentioned only as ways to avoid comparing. Nothing here is advice.
- Wolfram MathWorld: merge sortVon Neumann and the date.
- NVIDIA: merge sort explainedHow merge sort works.
- Wikipedia: comparison sortThe lower bound on comparisons.
- UC Irvine ICS 161: design and analysis of algorithmsThe log of n factorial and Stirling.
- GeeksforGeeks: lower bound for comparison sortingThe decision tree argument.
- Sort and Visualize: why n log n is the lower boundWhy comparing cannot go lower.
- William & Mary: sorting (chapter 7)Inversions and adjacent swaps.
- University of Hong Kong: sorting, searching and selectionQuadratic sorts.
- Baeldung: insertion sort vs bubble sortHow the two methods compare.
- Interview Kickstart: bubble, selection and insertion sortCosts of the simple methods.
- Medium: sorting in linear timeWays round the comparison floor.