Comparison-Based Sorting


Comparison-Based Sorting

Simon
Today we’re looking at sorting: how a few basic algorithms work, what their performance looks like, and how fast a comparison-based sort can possibly be. Start with the problem itself: we have an array of n items and a consistent way to compare them, such as less than or greater than. We want the same items back in order, say from least to greatest.

Corey
And sorting can have extra requirements beyond getting the values into order. One important example is stability. A stable sort preserves the previous relative order of items that compare as equal.

Simon
Think of a spreadsheet with people sorted by first name, and then sorted by last name using a stable sort. If two people share a last name, they remain in their first-name order. Stability matters whenever that earlier ordering carries information you want to keep.

Corey
Let’s begin with insertion sort. It processes items one at a time, finding the right place for each item among the ones already handled. Larger items shift to the right to make room, rather like inserting a new card into an ordered hand.

Simon
That shifting means insertion sort can work in place: it rearranges the array without needing a separate result array. It is also stable when equal items are inserted without passing one another. But its overall running time is O(n²), which becomes costly as the input gets large.

Corey
Selection sort takes a different route. At each position, it finds the minimum among the items that are not sorted yet, swaps that minimum into place, and then moves on. Once the first minimum is placed, for example, index zero is settled; then it finds the next minimum for index one.

Simon
It can be done in place. It can also be made stable if the items are moved carefully, rather than simply relying on swaps that could change the order of tied items. But it still takes O(n²) time, and it’s a slow option for large arrays.

Corey
Bubble sort repeatedly scans adjacent, unsorted pairs and swaps a pair when it’s out of order. On each pass, large items move toward the far end of the array, so the maximum can reach its proper position. The algorithm can also stop if a full pass makes no swaps.

Simon
And after a pass, it can avoid revisiting the part that was already settled, stopping at the last position that needed a swap. Bubble sort is stable and in place, and it remains O(n²) overall. Its best performance is on an array that’s nearly sorted already.

Corey
Now for a major improvement: merge sort, a divide-and-conquer algorithm. It keeps splitting the array into smaller parts until each part has one item, which is already sorted, then combines those parts in sorted order.

Simon
The combining step is the key. To merge two sorted lists, compare their first remaining items, take the smaller one, and repeat. You don’t compare every item with every other item; you advance through the lists, choosing the next smallest item each time.

Corey
For instance, merge the sorted lists 27 and 16, 38. The first choice is 16, then 27, then 38. As recursion builds the larger result, it uses the same idea: compare the fronts of the two sorted halves and take the smaller.

Simon
If the halves contain 12, 27, 38 and 16, 27, 39, the choices begin 12, then 16, and then one of the tied 27s. Either 27 can come first, but choosing consistently preserves the original order of equal items, which is how merge sort can be stable.

Corey
Merge sort is easiest to write using extra memory to copy and merge the portions of the array. It can be done in place, but that version is more complicated. Its running time is O(n log n): there are about log n levels of splitting, and merging across each level takes O(n) work.

Simon
It’s also easy to parallelize: separate portions can be handled by different threads or processes before their results are merged. That makes merge sort a useful contrast with the simple quadratic-time algorithms.

Corey
Heapsort uses a heap, an array-based structure that lets us find the maximum efficiently. Build or maintain a max-heap, take its maximum, and put it at the end of the array. Then treat that final position as sorted, restore the heap property in the remaining portion, and repeat.

Simon
Each maximum extraction takes O(log n) while maintaining the heap, and doing that n times gives heapsort O(n log n) worst-case time. It’s in place because the heap lives in the array. But it isn’t stable: a heap doesn’t preserve the original relative order of equal items.

Corey
Quicksort also divides the problem, but it starts by choosing a pivot. It partitions the other values so those lower than the pivot go to one side and those higher go to the other, then recursively sorts the two sides.

Simon
During partitioning, the algorithm finds items on the wrong sides and swaps them. When the partition is done, the pivot is in its final position, so recursive calls can ignore it. Quicksort can work in place by sorting ranges within the same array, and it has no merge step.

Corey
The pivot choice makes a big difference. A good pivot splits the data roughly in half, but a very bad one leaves almost everything on just one side. If the input is already sorted and we repeatedly pick the lowest value, for example, each pivot leaves an empty left side and a large right side.

Simon
That repeated imbalance leads to quicksort’s O(n²) worst case. With randomly selected pivots, its average behavior is O(n log n), and in practice it is often faster than other algorithms in that average-case category. Quicksort is not stable, because partition swaps can change the relative order of equal items.

Corey
So the labels matter: merge sort and heapsort provide O(n log n) worst-case behavior, while quicksort has O(n log n) average behavior but O(n²) worst-case behavior. A worst-case bound tells us what can happen, though it doesn’t always capture what we’ll usually experience.

Simon
The scale difference between O(n²) and O(n log n) can be enormous. The source’s rough illustration is that insertion sort on a few thousand items can feel instant, while a million might take hours on a typical computer, and a billion could take years on a home computer.

Corey
By comparison, merge sort is described as effectively instant up to millions of items, though billions could take minutes on a home computer. Quicksort, despite its bad worst case, can also be in the minutes category for billions in the stated practical comparison. Those are illustrations, not guarantees for every machine or input.

Simon
Now we can ask a deeper question: can any comparison-based sorting algorithm do better than O(n log n) in the worst case? To answer it, imagine a decision tree. Each internal node represents a comparison, and its two branches represent the possible outcomes.

Corey
Before any comparisons, every possible ordering of the items is still possible. Each comparison rules out some possibilities. As an algorithm makes comparisons, it follows a path through the tree until it reaches a leaf that identifies the required ordering.

Simon
For three items A, B, and C, one comparison might tell us whether A is less than B. Depending on the result, some possible orders are eliminated, and further comparisons narrow the choices. Different inputs can follow different paths, but every possible run corresponds to a root-to-leaf path.

Corey
If the items are distinct, there are n factorial possible input orderings, so a correct decision tree needs at least n factorial leaves. A binary tree of height h can have at most 2 to the h leaves. Therefore, in the worst case, the height must be at least log base two of n factorial.

Simon
And log of n factorial grows on the order of n log n. One way to see the shape is to expand the factorial: log of n factorial equals log n plus log of n minus one, plus log of n minus two, and so on. Even just a substantial portion of those terms gives a lower bound proportional to n log n.

Corey
So no comparison-based sorting algorithm can guarantee a worst-case running time better than Ω(n log n). Since merge sort and heapsort achieve O(n log n) worst-case time, that lower bound tells us the comparison-based category is already at the optimal order of growth.

Simon
That doesn’t mean every sort has every desirable feature. Some sorts are stable, some are in place, and the best-performing choices don’t necessarily combine both. But among comparison-based methods, n log n is the fundamental worst-case limit.

Corey
And the limit is specifically about sorting by comparisons. Other approaches can avoid comparisons, so they aren’t ruled out by this decision-tree argument. That’s the next direction to explore: sorting methods that use information other than pairwise comparisons.

Ask anything
We've read this whole study set, so questions about it get the best answers.