Skip to content
SimpleScope

Sorting

Merge sort vs Counting sort

Merge sort and Counting sort both put an array in order, in different ways. Merge sort: divide and conquer: split, sort each half, merge. 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 merge sort takes O(n log n) in the worst case. Counting sort is faster only when k and d are small compared with n; merge sort makes no assumption about the values.

At a glance

PropertyMerge sortCounting sort
TechniqueDivide and conquer: split, sort each half, mergeCount 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 log n)O(n + k)
Extra spaceO(n)O(n + k)
Stable (equal values keep their order)YesYes
In place (no extra array)NoNo
Needs sorted inputNoNo

When to choose each

Choose merge sort when

you need a guaranteed O(n log n) time or a stable sort.

Avoid it when

memory is tight.

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.

InputMerge sortCounting sort
Mixed3447
Already sorted3147
Reversed2947
Nearly sorted3147
Duplicates3247

See them run

More comparisons