Comparison Sort
Example
const sorted = prices.sort((a, b) => a > b);
console.log(sorted);const sorted = prices.toSorted((a, b) => a - b);
console.log(sorted);A boolean comparator never returns a negative value, so order is undefined; toSorted() also leaves the original array untouched.
Common mistakes
- Writing
(a, b) => a > band getting an unsorted result. - Calling
sort()on numbers and getting[1, 10, 2].
Key points
- Comparators passed to
sort()return a number (negative, zero, positive), not a boolean. - Numeric arrays are sorted with
(a, b) => a - b, since the defaultsort()compares strings. - The comparator is consistent: if
a < bandb < c, thena < c.
Interview questions
Why can't a comparison sort beat O(n log n)?
There are n! possible orders, and each comparison gives one yes/no answer, so at least log2(n!) comparisons are needed, which is about n log n.
Is JavaScript's Array.prototype.sort a comparison sort?
Yes, it only uses the comparator's results. The spec requires it to be stable.
Which sorts are not comparison sorts?
Counting sort, radix sort and bucket sort use the values themselves, so they can run in linear time on suitable data.
