Comparison-Based Sorting
Comparison-Based Sorting Algorithms
Sorting problem and key properties
A sorting algorithm takes an input collection of n items and produces the same items in a specified order. For example, sorting in ascending order places items from least to greatest. Sorting in descending order is equally possible.
Comparison-based sorting assumes that items can be compared consistently—for example, using “less than” and “greater than” relationships. The algorithm learns how items should be ordered by comparing them.
Two useful properties describe how a sorting algorithm uses and rearranges data:
Stable sorting: Items with equal sort keys retain their relative order from the input. This matters when sorting records by multiple fields. For example, sorting a list by last name after it has already been sorted by first name preserves first-name order among people with the same last name.
In-place sorting: The algorithm uses little additional storage, typically rearranging items within the input array rather than constructing a separate array proportional in size to the input. The exact amount of auxiliary memory depends on the implementation.
Stability and in-place operation are independent properties. An algorithm may have one, both, or neither.
Simple quadratic-time algorithms
Insertion sort
Insertion sort builds a sorted portion of the array one item at a time.
Consider the next item in the unsorted portion.
Compare it with items earlier in the array.
Shift larger items one position to the right until the correct position is available.
Insert the item there.
The process resembles inserting a new card into an already ordered hand of cards.
Stability: Stable, provided equal items are not moved past one another.
Space: In-place; it only needs a small amount of extra storage.
Time: Worst-case and average-case time are O(n2). The best case is O(n) when the input is already sorted, because each item requires very little work.
Insertion sort is simple and can be effective for small or nearly sorted inputs, but its quadratic growth makes it unsuitable for large, disordered inputs.
Selection sort
Selection sort repeatedly finds the smallest item in the unsorted portion and places it at the next output position.
Find the minimum item in the entire unsorted portion.
Move it to the first unsorted position.
Treat that position as sorted and repeat on the remaining items.
After the first pass, the minimum is in its final position. After the second, the two smallest items are in their final positions, and so on.
Stability: The standard version that swaps the minimum into position is not stable. Stability can be achieved by shifting items instead of performing a swap that changes the order of equal items.
Space: In-place.
Time: O(n2) in the best, average, and worst cases, because the algorithm repeatedly scans the remaining unsorted portion to find its minimum.
Selection sort performs a predictable number of comparisons, but its quadratic running time makes it slow for large inputs.
Bubble sort
Bubble sort repeatedly examines adjacent pairs and swaps a pair when it is out of order. During a pass, large items move toward the far end of the array.
Scan adjacent pairs in the unsorted portion.
Swap any pair that is out of order.
Repeat passes until a pass completes without a swap.
An implementation can also stop scanning at the last position changed in the previous pass, because positions beyond it are already in order.
Stability: Stable if equal items are not swapped.
Space: In-place.
Time: Worst-case and average-case time are O(n2). With an early-stop check, its best case is O(n) for an already sorted array.
Bubble sort can benefit from nearly sorted input, but it remains inefficient for large, disordered arrays.
Divide-and-conquer sorting
Merge sort
Merge sort uses the divide-and-conquer strategy: it divides a problem into smaller problems, solves them, and combines their results.
Divide: Split the array into two smaller parts.
Recur: Sort each part recursively.
Combine: Merge the two sorted parts into one sorted array.
A one-item array is already sorted, so recursion continues until the parts contain one item each (or until similarly small base cases are reached). The sorted parts are then merged upward through the recursion.
During a merge, the algorithm compares the first unmerged item in each sorted part. It copies the smaller item into the result and continues until all items have been included. For example, merging [27,38] and [16] selects 16 first, then 27, then 38.
Stability: Stable when equal items are taken from the left portion before equal items from the right.
Space: The straightforward implementation uses additional storage proportional to the array size, typically O(n). In-place versions exist, but are more complicated.
Time: O(nlogn) in the best, average, and worst cases.
The recurrence behind the running time is that the array is divided into about logn levels of subproblems, while merging across any one level takes O(n) total work. Thus the total work is O(nlogn).
Merge sort is also well suited to parallel execution: the two halves can be sorted independently before they are merged.
Heapsort
Heapsort uses a max-heap, a data structure in which the largest item is available at the root.
Arrange the items into a max-heap.
Remove the maximum item and place it at the end of the array.
Treat that end position as sorted and restore the heap property in the remaining portion.
Repeat until the heap is empty.
The heap occupies part of the array. As each maximum is moved to its final position, the portion still treated as a heap becomes smaller.
Stability: Not stable; heap operations can change the relative order of equal items.
Space: In-place.
Time: O(nlogn) in the worst case. Extracting a maximum and restoring the heap takes O(logn), and this is done for about n items. Building the initial heap can be done in O(n) time.
Heapsort provides a worst-case O(nlogn) guarantee while using little additional memory.
Quicksort
Quicksort also uses divide and conquer, but it divides the array through partitioning around a chosen item called the pivot.
Choose a pivot.
Partition the array so that items less than the pivot go to one side and items greater than the pivot go to the other.
Once partitioning is complete, the pivot is in its final sorted position.
Recursively sort the portions on either side of the pivot.
The pivot’s final position can be excluded from further recursive calls. Quicksort typically modifies the array within index ranges, so it does not need a merge step that constructs a new full array.
Stability: Not stable; partitioning can move equal items past one another.
Space: The partitioning can be done in-place. Recursive calls still require some stack space.
Average-case time: O(nlogn).
Worst-case time: O(n2).
The worst case occurs when repeated pivots divide the input very unevenly—for example, if each pivot is the smallest or largest remaining item. A sorted input can trigger this behavior with a deterministic pivot rule that repeatedly chooses an endpoint. Randomized pivot selection makes consistently poor splits less likely, but does not remove the theoretical worst case.
In practice, quicksort is often very fast on average and can outperform other O(nlogn) algorithms, despite having a worse worst-case bound.
Comparing the algorithms
Quadratic-time sorts
Insertion sort: Stable and in-place; useful for small or nearly sorted inputs.
Selection sort: In-place; standard swapping version is not stable; performs repeated minimum searches.
Bubble sort: Stable and in-place; can stop early when the array is already sorted, but is generally inefficient on large inputs.
Their quadratic running times mean that increasing the input size can cause work to grow rapidly. For example, multiplying the input size by 10 can multiply quadratic work by roughly 100.
O(nlogn) sorts
Merge sort: Stable, usually not in-place in its straightforward form, and has a reliable O(nlogn) time bound.
Heapsort: In-place and has a worst-case O(nlogn) bound, but is not stable.
Quicksort: Usually in-place apart from recursion and often very fast in practice; average time is O(nlogn), but worst-case time is O(n2).
No algorithm necessarily has every desirable feature. Choosing a sorting algorithm involves considering input size, input order, memory limits, stability requirements, and whether worst-case guarantees are important.
Why algorithm choice matters
The difference between O(n2) and O(nlogn) becomes substantial as n grows. A quadratic algorithm may feel instantaneous on a few thousand items but become impractical on very large inputs. An O(nlogn) algorithm can handle much larger inputs because its work grows more slowly.
Actual run times depend on hardware, implementation, and the data. Complexity classes describe how the work scales as input size grows; they do not guarantee a particular number of seconds.
A lower bound for comparison-based sorting
Upper bounds describe how much time a particular algorithm may take. A lower bound asks how little time any algorithm in a specified model could possibly take. For comparison-based sorting, a decision-tree argument shows that sorting requires at least on the order of nlogn comparisons in the worst case.
Decision-tree model
A comparison-based sorting algorithm can be represented by a decision tree:
Each internal node represents a comparison between two items.
Each outcome of that comparison leads to a child node.
Each leaf represents a final ordering that the algorithm can identify.
For example, with three items A, B, and C, a comparison such as whether A<B divides the possible outcomes into branches. Further comparisons narrow down which ordering is correct.
Every possible input ordering must lead to an appropriate leaf. If all items are distinct, there are n! possible permutations, so the tree must have at least n! leaves.
Height and number of comparisons
A decision tree of height h can have at most 2h leaves, because each comparison has at most two outcomes. Therefore, to distinguish all n! input permutations, the height must satisfy
which gives
Thus, in the worst case, a comparison-based sorting algorithm must perform at least log2(n!) comparisons.
A comparison does not always divide the remaining possible orderings exactly in half. The argument relies instead on the fact that a binary decision tree of a given height cannot have more than 2h leaves.
Why the bound is Ω(nlogn)
The factorial can be expanded as
Taking logarithms turns the product into a sum:
This sum grows on the order of nlogn. More precisely, Stirling’s approximation gives
Therefore, every comparison-based sorting algorithm requires Ω(nlogn) comparisons in the worst case. Merge sort and heapsort achieve O(nlogn) worst-case time, so their asymptotic worst-case performance matches this lower bound. No comparison-based algorithm can have a better worst-case growth rate than nlogn.
Key takeaway: Comparison-based sorting has a worst-case lower bound of Ω(nlogn). Algorithms such as merge sort and heapsort match that bound asymptotically.
This lower bound applies specifically to sorting methods that rely on comparisons. Other sorting approaches can use additional information about the keys and avoid the comparison-only model, so the comparison-based lower bound does not automatically apply to them.

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