# Comparison Sort

> The Comparison Sort is a type of algorithms that sort elements by comparing pairs to determine their order.

## What is a comparison sort and why is it at least O(n log n)?

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

- Topic: Sorting Algorithms
- Type: concept

## Example

Wrong:

```js
const sorted = prices.sort((a, b) => a > b);
console.log(sorted);
```

Right:

```js
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.

## Related cards

- [Quick Sort](https://wonderium.dev/algorithms/quick-sort.md)
- [Merge Sort](https://wonderium.dev/algorithms/merge-sort.md)
- [Counting Sort](https://wonderium.dev/algorithms/counting-sort.md)
- [.sort()](https://wonderium.dev/js/array-sort.md)
- [O(n log n)](https://wonderium.dev/algorithms/o-n-log-n.md)

---

- Level: [Algorithms](https://wonderium.dev/algorithms.md)
- HTML version: https://wonderium.dev/algorithms/comparison-sort
- Last updated: 2026-11-25
