Professional Documents
Culture Documents
Introduction To Algorithms Introduction To Algorithms: Comparison Sorting Review P G
Introduction To Algorithms Introduction To Algorithms: Comparison Sorting Review P G
Introduction To Algorithms Introduction To Algorithms: Comparison Sorting Review P G
p Sorting
g Review
Comparison
p Sorting
g Review Comparison
p Sorting
g Review
Counting
g Sort Counting
g Sort
1 CountingSort(A, B, k)
z Depends on assumption about the 2 for i=1 to k
numbers being sorted 3 C[i]= 0; This is called
a histogram.
z Assume numbers are in the range 1..
1 k 4 for j=1
j 1 to n
5 C[A[j]] += 1;
z The algorithm: 6 for i=2 to k
z IInput:
t A[1..n],
A[1 ] where
h A[j] ∈ {1,
{1 22, 3
3, …, k} 7 C[i] = C[i] + C[i
C[i-1];
1]
8 for j=n downto 1
z Output: B[1..n], sorted (not sorted in place)
9 B[C[A[j]]] = A[j];
z Also: Array C[1..k] for auxiliary storage 10 C[A[j]] -= 1;
Counting
g Sort Example
p Counting
g Sort
1 CountingSort(A, B, k)
2 for i=1 to k Takes time O(k)
3 C[i]= 0;
4 for j=1
j 1 to n
5 C[A[j]] += 1;
6 for i=2 to k
Takes time O(n)
7 C[i] = C[i] + C[i
C[i-1];
1]
8 for j=n downto 1
9 B[C[A[j]]] = A[j];
10 C[A[j]] -= 1;
Counting
g Sort Counting
g Sort