4 - DS - TAM - Counting Sort
4 - DS - TAM - Counting Sort
Counting sort
No comparisons between elements!
But…depends on assumption about the numbers
being sorted
We assume numbers are in the range 1.. K
The algorithm:
Input: A[1..N], where A[j] {1, 2, 3, …, K}
Output: B[1..N], sorted
Also: Array C[1..K] for auxiliary storage
28-Oct-21 2
(i.e., frequencies)
(r=6)
3
C (frequencies) Cnew (cumulative sums)
4
Start from the last element of A
A 2 5 3 0 2 3 0 3
0 1 2 3 4 5
Cnew 2 2 4 7 7 8
5
1 2 3 4 5 6 7 8 0 1 2 3 4 5
A 2 5 3 0 2 3 0 3 Cnew 2 2 4 7 7 8
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
B 3 B 0 3
0 1 2 3 4 5
0 1 2 3 4 5
Cnew 2 2 4 6 7 8 Cnew 1 2 4 6 7 8
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
B 0 3 3 B 0 2 3 3
0 1 2 3 4 5
0 1 2 3 4 5
Cnew 1 2 4 5 7 8 Cnew 1 2 3 5 7 8
6
1 2 3 4 5 6 7 8
A 2 5 3 0 2 3 0 3
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
B 0 0 2 3 3 B 0 0 2 3 3 3 5
0 1 2 3 4 5 0 1 2 3 4 5
C 0 2 3 5 7 8 C 0 2 3 4 7 7
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
B 0 0 2 3 3 3 B 0 0 2 2 3 3 3 5
0 1 2 3 4 5
C 0 2 3 4 7 8
7
COUNTING SORT
1 CountingSort(A, B, k)
2 for I=1 to K
3 C[I]= 0;
4 for J=1 to N
5 C[A[J]] += 1;
6 for I=2 to K
7 C[I] = C[I] + C[I-1];
8 for J=N down to 1
9 B[C[A[J]]] = A[J];
10 C[A[J]] -= 1;
B : , 1, , , , , 4, B : , 1, , , , 4, 4,
C : 1, 2, 4, 6, 7, 8 C : 1, 2, 4, 5, 7, 8
A : 3, 6, 4, 1, 3̂, 4, 1, 4 A : 3, 6, 4, 1̂, 3, 4, 1, 4
B : , 1, , 3, , 4, 4, B : 1, 1, , 3, , 4, 4,
C : 1, 2, 3, 5, 7, 8 C : 0, 2, 3, 5, 7, 8
A : 3, 6, 4̂, 1, 3, 4, 1, 4 A : 3, 6̂, 4, 1, 3, 4, 1, 4
B : 1, 1, , 3, 4, 4, 4, B : 1, 1, , 3, 4, 4, 4, 6
C : 0, 2, 3, 4, 7, 8 C : 0, 2, 3, 4, 7, 7
A : 3̂, 6, 4, 1, 3, 4, 1, 4
B : 1, 1, 3, 3, 4, 4, 4, 6
C : 0, 2, 2, 4, 7, 7
COUNTING SORT
Why don’t we always use counting sort?
Because it depends on range K of elements
Could we use counting sort to sort 32 bit
integers? Why or why not?
Answer: no, K too large (232 = 4,294,967,296)
28-Oct-21 12