Skip to main content
COUNTING SORT
Design and Analysis of Algorithm
COUNTING SORT
 Step-1: Create a count array to store the count of
each unique object.
 Step-2: Modify count array by adding the previous
number.
 Step-3: Create output array by decrese count array.
Let the Array in range 0 to 5
1 4 3 2 3 5 2
Create an array that will hold the count of each number, with index
ranges from 0 to 5
Count
Input
0 1 2 2 1 1
[0] [1] [2] [3] [4] [5]
Modify count array by adding the previous number:
Input
1 4 3 2 3 5 2
Sum Count 0 1 3 5 6 7
[0] [1] [2] [3] [4] [5]
Output each object from the input sequence followed by
decreasing count by 1:
1 4 3 2 3 5 2
Input
Sum Count 0 1 3 5 6 7
[0] [1] [2] [3] [4] [5]
output
[1] [2] [3] [4] [5] [6] [7]
1 4 3 2 3 5 2
Input
Sum Count 0 1 3 5 1 1
[0] [1] [2] [3] [4] [5]
1output
Output each object from the input sequence followed by
decreasing count by 1:
[1] [2] [3] [4] [5] [6] [7]
1 4 3 2 3 5 2
Input
0 0 3 5 6 7
[0] [1] [2] [3] [4] [5]
1 4output
[1] [2] [3] [4] [5] [6] [7]
Sum Count
1 4 3 2 3 5 2
Input
0 0 3 5 5 7
[0] [1] [2] [3] [4] [5]
1 3 4output
[1] [2] [3] [4] [5] [6] [7]
Sum Count
1 4 3 2 3 5 2
Input
0 0 3 4 5 7
[0] [1] [2] [3] [4] [5]
1 2 3 4output
[1] [2] [3] [4] [5] [6] [7]
Sum Count
1 4 3 2 3 5 2
Input
0 0 2 4 5 7
[0] [1] [2] [3] [4] [5]
1 2 3 3 4output
[1] [2] [3] [4] [5] [6] [7]
Sum Count
1 4 3 2 3 5 2
Input
0 0 2 3 5 7
[0] [1] [2] [3] [4] [5]
1 2 3 3 4 5output
[1] [2] [3] [4] [5] [6] [7]
Sum Count
1 4 3 2 3 5 2
Input
0 0 2 3 5 6
[0] [1] [2] [3] [4] [5]
1 2 2 3 3 4 5output
[1] [2] [3] [4] [5] [6] [7]
Sum Count
1 4 3 2 3 5 2
Input
0 0 1 3 5 6
[0] [1] [2] [3] [4] [5]
1 2 2 3 3 4 5output
[1] [2] [3] [4] [5] [6] [7]
Sum Count
ARRAY IS NOW SORTED
TIME COMPLEXITY
for i<-1 to k do………………………..constant time
c[i]<- 0……………………………..constant time
for j<- 1 to n do…………………………………n time
c[A[j]]<- c[A[j]]+1……………………………………..n time
for i<-2 to k do……………………………………….constant time
c[i]<- c[i]+c[i-1]………………………………………..constant time
for j<- n down to 1 do…………………………………n
B[c[A[i]]]<- A[j]……………………………………………………..n
C[A[i]]<- C[A[j]] +1…………………………………………….n
T(n) =c+c+n+n+c+c+n+n+n
=5n+4c
Big(O)=n