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 ¬ 1 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
2006-10-24
06:10:07
·
4 answers
·
asked by
Wattsie
3
in
Computers & Internet
➔ Programming & Design