Sorting
Counting sort vs Radix sort
Counting sort and Radix sort both put an array in order, in different ways. Counting sort: count each value, turn the counts into positions and place the values, with no comparisons. Radix sort: sort digit by digit, least significant first, with a stable counting sort for each digit. Neither compares values. Counting sort takes O(n + k) and Radix sort takes O(d (n + k)), where k is the number of possible values (or digit values) and d the number of digits (radix sort).
At a glance
| Property | Counting sort | Radix sort |
|---|---|---|
| Technique | Count each value, turn the counts into positions and place the values, with no comparisons | Sort digit by digit, least significant first, with a stable counting sort for each digit |
| Compares values with each other | No | No |
| Best case time | O(n + k) | O(d (n + k)) |
| Average case time | O(n + k) | O(d (n + k)) |
| Worst case time | O(n + k) | O(d (n + k)) |
| Extra space | O(n + k) | O(n + k) |
| Stable (equal values keep their order) | Yes | Yes |
| In place (no extra array) | No | No |
| Needs sorted input | No | No |
When to choose each
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.
Choose radix sort when
many integers or fixed-length keys have few digit positions (d is small).
Avoid it when
the array is small, or the keys are long.
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. Radix sort makes no comparisons, so its count is writes only. The lesson always runs 3 digit passes, even on these one-digit numbers.
| Input | Counting sort | Radix sort |
|---|---|---|
| Mixed | 47 | 141 |
| Already sorted | 47 | 141 |
| Reversed | 47 | 141 |
| Nearly sorted | 47 | 141 |
| Duplicates | 47 | 141 |
See them run
More comparisons
- Bubble sort vs Selection sort
- Bubble sort vs Insertion sort
- Bubble sort vs Merge sort
- Bubble sort vs Quick sort
- Bubble sort vs Heap sort
- Bubble sort vs Counting sort
- Bubble sort vs Radix sort
- Selection sort vs Insertion sort
- Selection sort vs Merge sort
- Selection sort vs Quick sort
- Selection sort vs Heap sort
- Selection sort vs Counting sort
- Selection sort vs Radix sort
- Insertion sort vs Merge sort
- Insertion sort vs Quick sort
- Insertion sort vs Heap sort
- Insertion sort vs Counting sort
- Insertion sort vs Radix sort
- Merge sort vs Quick sort
- Merge sort vs Heap sort
- Merge sort vs Counting sort
- Merge sort vs Radix sort
- Quick sort vs Heap sort
- Quick sort vs Counting sort
- Quick sort vs Radix sort
- Heap sort vs Counting sort
- Heap sort vs Radix sort