Lesson 121 of 296
Sorting and custom comparators
What you will learn
- How fast sorting is and why
- How JavaScript's sort works
- Comparators for numbers, strings and objects
- Sorting by several keys
- When sorting first makes a problem easier
- How merge sort and quicksort work
On this page
The cost of sorting
Comparison-based sorting (deciding order by comparing pairs) cannot be faster than O(n log n) in general. JavaScript's sort is O(n log n) and stable (equal items keep their order) since ES2019.
The default sort trap (Lesson 61)
[10, 9, 1].sort() gives [1, 10, 9], because the default compares as strings. Always pass a comparator for numbers.
Comparators
A comparator returns a negative number if a should come first, positive if b should come first, 0 if equal.
function sortNumbersAsc(nums: number[]): number[] {
return [...nums].sort((a, b) => a - b);
}
type Person = { name: string; age: number };
function sortPeople(people: Person[]): Person[] {
return [...people].sort(
(a, b) => a.age - b.age || a.name.localeCompare(b.name)
);
}sortPeople sorts by age, and for the same age, by name. The || moves to the second rule when the first gives 0.
Copy first ([...nums]) or use toSorted, because sort changes the original array.
Sorting makes many problems easier
Once data is sorted:
- Duplicates are next to each other.
- You can use two pointers (Lesson 123) and binary search (Lesson 131).
- Overlapping intervals can be merged in one pass (Lesson 144).
Example: Contains Duplicate by sorting, O(n log n) time, little extra space:
function containsDuplicateSorted(nums: number[]): boolean {
const sorted = [...nums].sort((a, b) => a - b);
for (let i = 1; i < sorted.length; i++) {
if (sorted[i] === sorted[i - 1]) return true;
}
return false;
}(The Set version in Lesson 122 is O(n) time but O(n) space: a trade-off to mention.)
How merge sort works
Merge sort is a divide and conquer algorithm:
- Split the array in half.
- Sort each half (by calling merge sort again).
- Merge the two sorted halves into one sorted array.
function mergeSort(nums: number[]): number[] {
if (nums.length <= 1) return nums;
const mid = Math.floor(nums.length / 2);
const left = mergeSort(nums.slice(0, mid));
const right = mergeSort(nums.slice(mid));
return mergeSorted(left, right);
}
function mergeSorted(a: number[], b: number[]): number[] {
const result: number[] = [];
let i = 0;
let j = 0;
while (i < a.length && j < b.length) {
if (a[i]! <= b[j]!) result.push(a[i++]!);
else result.push(b[j++]!);
}
while (i < a.length) result.push(a[i++]!);
while (j < b.length) result.push(b[j++]!);
return result;
}- There are about log n levels of splitting, and each level does O(n) merging work: O(n log n) always.
- Uses O(n) extra space. Stable.
- The
mergeSortedstep is itself a classic problem (merging two sorted lists, Lesson 133).
How quicksort works
- Pick a pivot item.
- Partition: move smaller items to its left and larger items to its right.
- Quicksort the left and right parts.
function quickSort(nums: number[]): number[] {
if (nums.length <= 1) return nums;
const pivot = nums[Math.floor(nums.length / 2)]!;
const less = nums.filter((n) => n < pivot);
const equal = nums.filter((n) => n === pivot);
const greater = nums.filter((n) => n > pivot);
return [...quickSort(less), ...equal, ...quickSort(greater)];
}(This readable version uses extra arrays. Real implementations partition in place.)
- Average O(n log n), but O(n²) worst case if the pivot is always the smallest or largest item. Choosing a random or middle pivot makes that unlikely.
- In-place versions use O(log n) stack space. Usually not stable.
Comparison of sorts
| Sort | Average | Worst | Extra space | Stable |
|---|---|---|---|---|
| Merge sort | O(n log n) | O(n log n) | O(n) | Yes |
| Quicksort | O(n log n) | O(n²) | O(log n) | No |
| Heap sort | O(n log n) | O(n log n) | O(1) | No |
| Insertion sort | O(n²) | O(n²) | O(1) | Yes (fast for tiny or nearly sorted arrays) |
| Counting sort | O(n + k) | O(n + k) | O(k) | Yes (only for small integer ranges k) |
Engines mix algorithms: V8 uses TimSort, a hybrid of merge sort and insertion sort that is very fast on partly sorted data.
How to say it in an interview
"Comparison sorting is O(n log n) at best. JavaScript's sort is stable but compares as strings by default, so I always pass a comparator, chain keys with OR, and copy first or use toSorted because sort mutates. Sorting often unlocks two pointers, binary search or interval merging. Merge sort splits, sorts halves and merges in guaranteed O(n log n) with O(n) space; quicksort partitions around a pivot, averaging O(n log n) but O(n squared) in the worst case."
Key words
| Word | Meaning |
|---|---|
| Comparator | A function that decides the order of two items |
| Stable sort | Equal items keep their original order |
| Divide and conquer | Split a problem, solve the parts, combine the results |
| Merge sort | Split in halves, sort, merge |
| Quicksort | Partition around a pivot, sort each side |
| Pivot | The item used to split the data in quicksort |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.