Counting Sort
| Operation | Method | Time | Adaptive? | In-Place? | Stable? | Online? |
|---|---|---|---|---|---|---|
| Counting sort | Non-Comparison | N | N | Y | N |
Idea
Counting sort is a sorting algorithm that works by counting the number of occurrences of each unique element in the input array and then using these counts to determine the position of each element in the sorted output array.
Pre-Conditions
- The numbers to sort are integers in an interval of
The Algorithm
Requirements:
- Input:
where is the size of the array is the upper bound integer of the range to sort
- Output:
is a sorted vector in a non-decreasing manner - Auxiliary Data Structure
is the vector of the occurrences of size , with possible indices
Steps:
- Allocation and Initialization of a vector of occurences
of size with indices in - Populate
starting from :count the occurrences of elements with same keys in . - Es:
, with is the count of times contains the number three.
- Es:
- Cumulative prefixed sum of values in C starting from
: count how many elements precede the current one represents the index of the element in the new sorted array - For each element in
, increase its value by the value in the previous index. This helps us find the right position in
- Populate
from to , to achieve stability. - Because an element might be repeated, we decrement the value of
every time it is read.
- Because an element might be repeated, we decrement the value of
python
void countingsort(array A, array B, int n, int k) {
Allocation C[0...k]; #aux data structure
#O(k)
for (i = 0 to k): #Initialization of C to 0
C[i] = 0;
#Theta(n)
for (i = 1 to n): # count occurrences of elements in A
C[A[i]]++;
#Theta(k)
for (i = 1 to k):
C[i] = C[i] + C[i-1] #prefixed sums
#Theta(n)
for (i = n down to 1):
B[--C[A[i]]] = A[i]; #insert and avoid duplicates or insertion in same positionvoid countingsort(array A, array B, int n, int k) {
Allocation C[0...k]; #aux data structure
#O(k)
for (i = 0 to k): #Initialization of C to 0
C[i] = 0;
#Theta(n)
for (i = 1 to n): # count occurrences of elements in A
C[A[i]]++;
#Theta(k)
for (i = 1 to k):
C[i] = C[i] + C[i-1] #prefixed sums
#Theta(n)
for (i = n down to 1):
B[--C[A[i]]] = A[i]; #insert and avoid duplicates or insertion in same positionExample:

Final Time Complexity:
- Usually best when
Conclusions
Pro:
- If
- It is a stable sorting algorithm, if we start from the end.
Cons:
- Not in-place (we use an auxiliary vector C[0..k])
- Only sorts numbers between 0 and k, restricted integer spectrum.
- If the interval of numbers go from 0 to
then it is not efficient: