Sorting Algorithms: Methods and Performance
Sorting algorithms all produce the same output; they differ in time, memory, stability and how they handle data that is already partly sorted. This overview compares them and links to each one.
How Sorting Algorithms Are Compared
Every sorting algorithm returns the same sorted list, so choosing one means comparing how it gets there. Four properties do most of the work.
Time, and which case. Quicksort is O(n log n) on average but O(n²) in its worst case; merge sort and heap sort are O(n log n) on every input. The worst case matters when someone else controls the input.
Extra space. An in-place sort needs only O(1) memory beyond the array: heap sort, insertion sort, and quicksort apart from its O(log n) recursion stack. Merge sort needs an O(n) buffer. In-place vs out-of-place sorting covers what that memory buys.
Stability. A stable sort keeps records with equal keys in their original order. Sort students by name, then stably by grade, and each grade stays in name order; an unstable sort can scramble it, as the tracer's selection sort does. Stable vs unstable sorting shows which sorts keep ties in order and why.
Adaptivity. An adaptive sort does less work on data that is already nearly sorted. Insertion sort makes n − 1 comparisons on sorted input and about n²/2 on reversed input. Real data is often partly ordered, so this counts.
At scale, memory access matters too. Quicksort's partition scans the array in order and uses the cache well; heap sort jumps between a parent and children far apart, which is why it usually loses to quicksort in practice despite the better worst case.
- n under about 20: constant factors decide, and insertion sort usually wins
- Equal keys in plain numbers: stability makes no visible difference
- Data on disk or flash: sequential access and number of writes start to matter
Why Comparison Based Sorting Cannot Beat n log n
A comparison based sorting algorithm learns about the input only by asking 'is x < y?'. Each answer is yes or no, so every run of the algorithm is a path down a binary decision tree whose leaves are the possible final orders.
n distinct values can arrive in any of n! orders, and the sort must be able to finish in each of them, so the tree needs at least n! leaves. A binary tree of height h has at most 2^h leaves, so h ≥ log₂(n!), which grows like n log₂ n. The height is the worst-case number of comparisons.
For 3 values that is log₂ 6 ≈ 2.6, so 3 comparisons; with only 2 there are 4 leaves for 6 orders and some input gets the wrong answer. For 8 values it is log₂ 40,320 ≈ 15.3, so at least 16.
Merge sort and heap sort reach this bound, so they are optimal among comparison sorts up to a constant factor. A sort that does better must get information some other way, by reading the values themselves.
The bound is about the worst case over all inputs. It does not stop a sort from being fast on easy inputs: Timsort takes O(n) on input that is already sorted.
- Lower bound: Ω(n log n) comparisons in the worst case
- Also true on average: most of the n! leaves are deep
- Not a limit on counting, radix or bucket sort, which do not compare
Types of Sorting Algorithms
The sorting techniques taught in data structure courses fall into two groups: those that compare pairs of values and those that use the values directly. Each one below has its own lesson.
Simple quadratic sorts. Bubble sort swaps neighbours that are out of order; it is easy to explain and slower than insertion sort in practice. Selection sort moves the smallest remaining value into place each pass; it always makes about n²/2 comparisons but at most n − 1 swaps, which helps only when writes are expensive. Insertion sort grows a sorted prefix; it is stable, in-place and O(n) on nearly sorted data, which is why libraries use it for small pieces.
Divide and conquer. Merge sort sorts both halves and merges them: O(n log n) always and stable, at the cost of an O(n) buffer. It suits linked lists, where merging relinks nodes instead of copying, and files too large for memory. Quicksort partitions around a pivot and is usually the fastest in practice; a poor pivot rule turns it O(n²), and the tracer shows a last-element pivot doing that on sorted input.
Heap based. Heap sort builds a heap in O(n) and removes the largest value n times: O(n log n) on every input with O(1) extra space, but not stable and not cache-friendly.
Gap based. Shell sort runs insertion sort over shrinking gaps so values travel far in one move. Its running time depends on the gap sequence; good sequences run well below n² on mid-sized arrays.
Non-comparison sorts. Counting sort tallies each value and rebuilds the array in O(n + k) for values in a range of size k. Radix sort runs a stable counting sort once per digit, O(d(n + k)), and depends on each pass being stable. Bucket sort spreads values into ranges and averages O(n) when the input is evenly spread. All three need something known about the keys.
| Algorithm | Average | Worst | Extra space | Stable | Adaptive |
|---|---|---|---|---|---|
| Bubble | O(n²) | O(n²) | O(1) | Yes | With early exit |
| Selection | O(n²) | O(n²) | O(1) | No | No |
| Insertion | O(n²) | O(n²) | O(1) | Yes | Yes, O(n) when sorted |
| Merge | O(n log n) | O(n log n) | O(n) | Yes | No |
| Quick | O(n log n) | O(n²) | O(log n) | No | No |
| Heap | O(n log n) | O(n log n) | O(1) | No | No |
| Counting | O(n + k) | O(n + k) | O(n + k) | Yes | — |
| Radix | O(d(n + k)) | O(d(n + k)) | O(n + k) | Yes | — |
- Quicksort's O(log n) space assumes it recurses into the smaller side first
- Bucket sort's worst case is whatever sorts the fullest bucket
Terms, operations, and practical uses
Sorting properties
- StableEqual keys retain their original relative order.
- In placeUses only a small amount of auxiliary storage beyond the input.
- AdaptiveExisting order reduces the work performed.
- Comparison lower boundAny comparison based sort needs
Ω(n log n)comparisons in the worst case.
Comparison methods
- Bubble sortSwaps adjacent pairs until a pass makes none.
- Selection sortTakes the smallest remaining value each pass.
- Insertion sortPlaces each new item into a sorted prefix.
- Merge sortSorts halves, then merges them linearly.
- QuicksortPartitions around a pivot, then sorts each side.
- HeapsortRemoves the extreme value from a heap, n times.
Non-comparison and hybrid
- Counting sortUses the value itself as an index, in O(n + k).
- Radix sortOne stable pass per digit, least significant first.
- Bucket sortSpreads values across ranges, then sorts each.
- Shell sortInsertion sort over shrinking gaps.
Code in Python, C++ and Java
def insertion_sort(values):
for i in range(1, len(values)):
current = values[i]
j = i - 1
while j >= 0 and values[j] > current:
values[j + 1] = values[j]
j -= 1
values[j + 1] = current
return values
print(insertion_sort([5, 2, 4, 1]))#include <iostream>
#include <vector>
using namespace std;
// Insertion sort: grow a sorted prefix by sliding each new value back into place.
void insertionSort(vector<int>& values) {
for (size_t i = 1; i < values.size(); ++i) {
int current = values[i];
int j = static_cast<int>(i) - 1;
while (j >= 0 && values[j] > current) { // shift larger values right
values[j + 1] = values[j];
--j;
}
values[j + 1] = current; // drop the key into the gap
}
}
int main() {
vector<int> values = {5, 2, 4, 1};
insertionSort(values);
cout << "[";
for (size_t i = 0; i < values.size(); ++i) {
if (i) cout << ", ";
cout << values[i];
}
cout << "]\n";
}import java.util.Arrays;
public class Main {
// Insertion sort: grow a sorted prefix by sliding each new value into place.
static void insertionSort(int[] values) {
for (int i = 1; i < values.length; i++) {
int current = values[i];
int j = i - 1;
while (j >= 0 && values[j] > current) { // shift larger values right
values[j + 1] = values[j];
j--;
}
values[j + 1] = current; // drop the key into the gap
}
}
public static void main(String[] args) {
int[] values = {5, 2, 4, 1};
insertionSort(values);
System.out.println(Arrays.toString(values));
}
}Step through it
Running on [5, 2, 8, 1, 7, 3, 6, 4] and more
What Libraries Use, and the Best Sorting Technique
Production libraries do not run the textbook versions. They use hybrids that combine the strengths above.
Timsort, used by Python's sorted and by Java's Arrays.sort for objects, is a stable merge sort that first finds runs that are already in order and merges those. Short runs are extended to 32 to 64 values with binary insertion sort. On sorted input it is O(n).
Introsort, used by C++ std::sort, starts as quicksort, switches to heap sort if the recursion goes deeper than about 2 log₂ n, which caps the worst case at O(n log n), and finishes partitions of 16 or fewer values with insertion sort. Java sorts arrays of primitives with a dual-pivot quicksort, where stability does not matter.
So the best sorting technique depends on the data, and the default answer is the library sort. Write your own only for a need it does not meet: stability where the library does not promise it, data on disk, or keys with known structure that counting or radix sort can exploit.
Quick rules: small or nearly sorted arrays, insertion sort; guaranteed O(n log n) with stability, merge sort; fastest typical in-memory sort, quicksort with a random or median-of-three pivot; O(1) extra space with a guarantee, heap sort; small integer keys, counting or radix sort.
- Sorting objects by several keys: sort by the least important key first, with a stable sort each time
- Partial order only (the k smallest): a heap or quickselect beats a full sort
- Practice: Sort Colors, Sort List, Kth Largest Element in an Array