Comparing Sorts — Algorithms

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…

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

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]

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

How to choose

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()

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.

What you will learn