Algo-Sim › Sorting & Divide and Conquer
Counting Sort
Easy · Sorting & Divide and Conquer · step through it in Java, Python and C++ on your own input
When values come from a small range, count how many of each there are and write them back in order. O(n + k) and no comparisons at all.
Problem
Sort nums, whose values all fall in a small range 0..k − 1, without comparing elements: count how many times each value occurs, then write the values back in order.
Constraints
- O(n + k) time and O(k) extra space
- Only practical when the range k is small compared with n
- Values here are 0–9
Edge cases to test
- All values equal
- A huge range with few values (wasteful)
- Negative values (shift by the minimum)
Follow-up questions
- How do you make it stable?
- Turn the counts into prefix sums and place items from the back: needed when sorting records by a key, as radix sort does.
- When is it the right tool?
- When the range k is O(n): sorting in O(n + k), e.g. ages, grades or bytes.
Solution
Java
public int[] countingSort(int[] nums) {
int[] count = new int[10];
for (int x : nums) count[x]++;
int i = 0;
for (int v = 0; v < 10; v++) {
for (int c = 0; c < count[v]; c++) {
nums[i++] = v;
}
}
return nums;
}Python
def counting_sort(nums):
count = [0] * 10
for x in nums:
count[x] += 1
i = 0
for v in range(10):
for _ in range(count[v]):
nums[i] = v
i += 1
return numsC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> countingSort(vector<int> &nums) {
vector<int> count = vector<int>(10);
for (int x : nums)
count[x]++;
int i = 0;
for (int v = 0; v < 10; v++) {
for (int c = 0; c < count[v]; c++) {
nums[i++] = v;
}
}
return nums;
}
};
More Sorting & Divide and Conquer problems
- Bubble Sort (Easy)
- Insertion Sort (Easy)
- Selection Sort (Easy)
- Merge Sort (Medium)
- Quick Sort (Lomuto) (Medium)
- Quick Sort (Hoare) (Medium)
- Radix Sort (LSD) (Medium)
- Bucket Sort (Medium)
- Kth Largest Element (Quickselect) (Medium)
- Count Inversions (Hard)
- Largest Number (Medium)