Sorting Algorithms: How a Computer Puts Things in Order, and What Each Way Costs
A recruitment board has just marked 20,000 written papers. The merit list goes up this evening: highest marks first, and for equal marks the smaller roll number first. By hand you could walk down the pile swapping any two neighbours that are the wrong way round, and repeat until a whole walk needs no swap. That works, and it is called bubble sort, but for 20,000 papers it can take up to 199,990,000 comparisons, about two hundred million. Now split the pile in half, let each half sort itself, and merge the two sorted halves. The same papers then need at most 267,233 comparisons: about 748 times less work, and nothing changed except the idea.
That is the story of this chapter. There are many ways to sort, each has a price, and the price is something you can count on your fingers for eight numbers and prove for eight million.
You arrive from the last lesson, where you learned to read a recurrence like T(n) = 2T(n/2) + n and solve it. This is where such recurrences come from: merge sort is T(n) = 2T(n/2) + n, and quick sort on a bad day is T(n) = T(n − 1) + n.
By the end you will be able to trace the standard sorts pass by pass and count their comparisons and swaps; say for each whether it is stable, in-place or adaptive, and give its best, average and worst time; write the merge and partition procedures; build a heap and sort with it; explain with a decision tree why no sort that compares keys can beat n log n, and how counting, radix and bucket sort slip past that limit; and choose a sort for a job, including a file bigger than memory. You will also know how the exam asks each of these.