You now know seven sorts (ways to sort data), from bubble sort to counting sort. This lesson puts all seven side by side, so you can choose. You will see which one is fast for your data, which one saves memory, and which one keeps items with equal values in their original order. No single sort wins on every kind of data.
Same data, different winners
In the Lab, four sorts race to sort the same 7 numbers. The winner is the sort that compares numbers the fewest times. These are the comparisons on three kinds of data:
| Data | Bubble | Insertion | Merge | Quick |
|---|---|---|---|---|
Shuffled [38, 27, 43, 3, 9, 82, 10] |
21 | 15 | 13 | 11 |
Nearly sorted [3, 9, 10, 27, 38, 82, 43] |
21 | 7 | 9 | 16 |
Reversed [82, 43, 38, 27, 10, 9, 3] |
21 | 21 | 11 | 21 |
- Shuffled data: quick sort wins.
- Nearly sorted: insertion sort wins by far, because almost every number only needs one comparison with the number to its left. Quick sort actually struggles: its pivot in the Lab is the rightmost number, and on this data that number is almost always the largest in its part.
- Reversed: merge sort wins. The other three sorts hit their worst case: 21 = 7 × 6 / 2 comparisons.
To keep it fair, each sort in the race gets its own copy of the same data. This code makes a copy of data, then sorts the copy:
const data = [38, 27, 43, 3, 9, 82, 10];
const sorted = [...data].sort((a, b) => a - b);
console.log(sorted); // [3, 9, 10, 27, 38, 43, 82]
console.log(data); // [38, 27, 43, 3, 9, 82, 10]
[...data]makes a copy of the arraydata.sortchanges the array it sorts, so without a copy, the originaldatawould change too.(a, b) => a - bis the compare function: a short function that takes two numbers,aandb. If the result is negative,agoes beforeb. For numbers, you must write it.
The comparison table
The table below uses Big-O, a way of writing how fast an algorithm's number of steps grows as the data grows. For 1,000 numbers, O(n) takes about 1,000 steps, O(n log n) about 10,000, and O(n²) about 1,000,000. The Best, Average and Worst columns give each sort's time in Big-O.
| Sort | Best | Average | Worst | Extra memory | Stable |
|---|---|---|---|---|---|
| Bubble | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection | O(n²) | O(n²) | O(n²) | O(1) | No |
| Insertion | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Merge | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick | O(n log n) | O(n log n) | O(n²) | O(log n) on average, O(n) worst | No |
| Heap | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Counting | O(n + k) | O(n + k) | O(n + k) | O(n + k) | Yes |
- Best usually happens on data that's already sorted. Bubble sort reaches O(n) only with the
swappedflag, which stops it as soon as a pass swaps nothing. The Lab's bubble sort has no such flag, so it always makes 21 comparisons. - Extra memory is the memory a sort uses besides the data's own array. O(1) means just a few variables. Merge sort needs an extra array as big as the data. The Lab's quick sort (partitioning in place) needs memory to record the recursive calls that haven't finished yet. On average about log n calls wait at the same time. On sorted data n calls wait, and with 10,000 numbers the code stops with
RangeError: Maximum call stack size exceeded. If it recurses only into the smaller side and handles the bigger side with a loop, at most log n calls wait. Counting sort needskcounting boxes (k = the range of values), plus an output array. - Stable means items with equal values keep their original order. For example, a list of transactions is already sorted by date, and then you sort it again by amount. A stable sort keeps transactions with the same amount in date order.
How to choose
- Small or nearly sorted data: insertion sort.
- Needs to be stable, or the worst-case time must be guaranteed: merge sort, which is always O(n log n).
- Shuffled data in memory, you want what's usually fastest: quick sort, with a random pivot or one in the middle, not at the right end as in the Lab.
- Very tight memory and a guaranteed worst-case time: heap sort.
- Whole numbers with a small range: counting sort.
In JavaScript, use arr.sort()
V8 is the JavaScript engine (the program that runs JavaScript) in Chrome and Node.js. Since 2018, V8 has used Timsort: a mix of insertion sort for small pieces and merge sort to join those pieces. Timsort is stable, O(n log n) in the worst case, and fast on nearly sorted data. Since ES2019 (the 2019 version of the JavaScript standard), sort must be stable in every browser.
So day to day, use arr.sort((a, b) => a - b). Writing your own sort is useful for learning, or for special cases like counting sort.
The compare function depends on the kind of data:
| Data | Compare function | Result |
|---|---|---|
| Numbers | (a, b) => a - b |
smallest to largest. Write (a, b) => b - a for largest to smallest |
| Text | (a, b) => a.localeCompare(b) |
["anna", "Zoe", "ben"] becomes ["anna", "ben", "Zoe"] |
| Objects | (a, b) => a.score - b.score |
a list of students in order of their score, smallest first |
Text needs a compare function too. ["anna", "Zoe", "ben"].sort() gives ["Zoe", "anna", "ben"], because without a compare function every capital letter goes before every small letter. localeCompare compares two texts by the rules of a language, so capital and small letters are sorted together.
⚠️ What surprises people about sort()
sort()with no compare function.[3, 9, 10, 27].sort()gives[10, 27, 3, 9]. Without a compare function, numbers are sorted as text, like words in a dictionary: 10 starts with 1, so it goes before 3. For numbers, always write(a, b) => a - b.- The original array changes.
sortsorts the array itself. If you still need the original, sort a copy:[...data].sort(...). You can also usedata.toSorted((a, b) => a - b), which every major browser has had since July 2023.toSortedgives a new sorted array, anddatadoes not change. - Forgetting about stability. Selection, quick and heap sort can change the original order of items with equal values. If that order matters, use merge sort or
arr.sort().
TL;DR: Pick a sort based on your data. Small or nearly sorted data: insertion sort, which is O(n) in its best case. You need a stable sort (items with equal values keep their original order), or a guaranteed O(n log n): merge sort, with O(n) extra memory. Shuffled data: quick sort, fastest on average, but O(n²) in the worst case and not stable. Tight memory: heap sort. Whole numbers with a small range of values (k): counting sort, O(n + k). In JavaScript, arr.sort((a, b) => a - b) uses Timsort (a mix of insertion sort and merge sort), which is stable and fast.
⚡ Same data, different winners
Guess first: four sorts (bubble, insertion, merge and quick sort) race on the nearly sorted data [3, 9, 10, 27, 38, 82, 43]. Which one compares numbers the fewest times?
Insertion sort, with just 7 comparisons. Almost every number only needs one comparison with the number to its left.
Meaning: No single sort wins on every kind of data. On shuffled data quick sort wins, and on reversed data merge sort does.
⚡ How to choose
Meaning: Small or nearly sorted data: insertion sort. You need a stable sort (items with equal values keep their original order) or a guaranteed O(n log n): merge sort. Shuffled data: quick sort with a random pivot or one in the middle. Tight memory: heap sort. Whole numbers with a small range of values: counting sort.
⚡ In JavaScript, use arr.sort()
Write:
const data = [38, 27, 43, 3, 9, 82, 10];
const sorted = [...data].sort((a, b) => a - b);
console.log(sorted); // [3, 9, 10, 27, 38, 43, 82]
console.log(data); // [38, 27, 43, 3, 9, 82, 10]
Guess first: (a, b) => a - b in that code is the compare function. What does [3, 9, 10, 27].sort() give, with no compare function?
[10, 27, 3, 9]. Without a compare function, numbers are sorted as text, like words in a dictionary: 10 starts with 1, so it goes before 3.
Meaning: [...data] makes a copy, because sort changes the original array. For numbers, you must write a compare function. V8, the JavaScript engine in Chrome and Node.js, uses Timsort (a mix of insertion sort and merge sort), which is stable.