Counting Sort
no comparisons
Assume n elements in range 1 to k. When k = O (n),
running time is O (n).
Arrays:
A[1 ... n] original unsorted array
B[1 ... n] array to hold sorted output
C[1 ... k] working array to hold counts
Counting-Sort ( A, B, k )
-
for i to k
-
do C[i] ¬ 0
-
for j ¬ 1 to length[A]
-
do C[A[j]] ¬
C[A[j]] + 1
-
// C[i] now contains the number of elements equal to k.
-
for i ¬ 2 to k
-
do C[i] ¬ C[i]
+ C[i-1]
-
// C[i] now contains the number of elements less than or
equal to i
-
for j ¬ length[A] downto 1
-
do B[C[A[j]]] ¬
A[j]
-
C[A[j]] ¬ C[A[j]] - 1
Each line below shows the step by step operation of counting
sort.
A |
3 |
6 |
4 |
1 |
3 |
4 |
1 |
4 |
|
C |
2 |
0 |
2 |
3 |
0 |
1 |
Cost of Counting Sort:
- O (k)
- O (n)
- O (k)
- O (n)
O ( n + k ) if k = O (n) = O (2 n) = O (n)
- In place: No
- Divide and conquer? No
- Stable: Yes (Numbers with equal values in A[] appear is same order
in B[].)
Why is its cost better than W ( n lg
n)? NO COMPARISONS!
|