The home where you level up

Save my spot

Comparison Sort

Term side of the Card.
Topic: Sorting Algorithms
Unit title: Comparison Sort
Categories: Concept
Explanation side of the Card

Explanation: The type of sorting algorithms that determines the order of elements by comparing them. Includes methods like Quick Sort, Merge Sort and Bubble Sort.

Example

Wrongjs
const sorted = prices.sort((a, b) => a > b);
console.log(sorted);
Rightjs
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 > b and 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 default sort() compares strings.
  • The comparator is consistent: if a < b and b < c, then a < 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.

The home where you level up

Daily 3-minute lessons to understand your AI's code.

No spam — just launch news.
Unsubscribe anytime. · Privacy Policy

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy