Academics · High School · Computer science
Type a list and step through four classic sorts and two searches, forward and back, with a sentence for every comparison. Guess the count first, then race all four on the same numbers.
Pick a list and an algorithm, then press Step. The arrow keys work on the bars too.
Loading the algorithm lab. If nothing appears, turn on JavaScript.
Every sort here does the same job. What differs is the rule for which two values to compare next, and that rule decides how the work grows.
Each pass carries the largest value left to the end. A pass with no swaps means the list is sorted, so a nearly sorted list finishes fast.
for each pass:
for each neighbor pair:
if left > right: swapTake the next value and shift larger ones right until it fits. This is how most people sort a hand of cards.
for each value after the first:
shift larger values right
drop the value in the gapThe fewest swaps of the four, at most n − 1, but always the same number of comparisons, however sorted the list already is.
for each position:
find the smallest after it
swap it into placeMerging two sorted runs takes at most one comparison per value placed. For 16 values that caps the work at 49 comparisons, against 120 for the other three.
sort(list):
sort(left half)
sort(right half)
merge the halvesAcademics · High SchoolFree
The same steps you watch are the ones that are counted.
A comparison is any time two values from the list are compared, or, in a search, any value checked against the one you are looking for. A move is a swap in bubble and selection sort, a shift or the final drop in insertion sort, and a copy back into the list in merge sort, so moves are counted the way each algorithm actually spends them.
Bubble sort here stops after a pass with no swaps; insertion sort stops each scan at the first value that is not larger; merge sort splits with the smaller half on the left and sends ties to the left run, which keeps equal values in their original order. Textbooks vary on these details, so a count can differ by a few from another book’s version of the same algorithm.
Every count on the page comes from the same steps you watch. Before the page was built, the four sorts and two searches were written again in Python with the same rules and run on 66 lists and 41 searches; the page’s counts are compared with those on every test run.
The timing column assumes 100 million comparisons a second to make the sizes comparable; real speed depends on the computer, the language and the data. Example lists are made up. Support: team@caveatacademic.com.