Skip to content
SimpleScope

Sorting

Quick sort vs Counting sort

Quick sort and Counting sort both put an array in order, in different ways. Quick sort: divide and conquer: partition around a pivot. Counting sort: count each value, turn the counts into positions and place the values, with no comparisons. Counting sort compares no values: it takes O(n + k), where k is the number of possible values (or digit values) and d the number of digits (radix sort), while quick sort takes O(n²) in the worst case. Counting sort is faster only when k and d are small compared with n; quick sort makes no assumption about the values.

At a glance

PropertyQuick sortCounting sort
TechniqueDivide and conquer: partition around a pivotCount each value, turn the counts into positions and place the values, with no comparisons
Compares values with each otherYesNo
Best case timeO(n log n)O(n + k)
Average case timeO(n log n)O(n + k)
Worst case timeO(n²)O(n + k)
Extra spaceO(log n)O(n + k)
Stable (equal values keep their order)NoYes
In place (no extra array)YesNo
Needs sorted inputNoNo

When to choose each

Choose quick sort when

you want a fast in-place sort on typical data.

Avoid it when

you need a worst-case guarantee or a stable sort.

Choose counting sort when

the values are whole numbers in a range k that is small compared with n.

Avoid it when

the range of values is large, or the values are not whole numbers.

The same inputs, counted

These numbers come from running both real implementations: operations (comparisons plus writes, a swap counting as two writes). Counting sort makes no comparisons, so its count is writes only. It includes the k + 1 cells of the count array.

InputQuick sortCounting sort
Mixed3147
Already sorted7547
Reversed5147
Nearly sorted6547
Duplicates2947

See them run

More comparisons