- Counting sort Algorithm was created by Harold H Seward in 1954.
- It takes the advantage of knowing the range of numbers in the array to be sorted.
- It assume that each of the n input elements is n integer in the range 1 to k, for some integer k.
- where K = O (n) the sort runs in O (n) time.
- It is a stable sort technique.
- In this sort same number in the sequence does not change .
For Example:
Number should preserve its position at the time of comparison if they are same.
Counting Sort Algorithm pseudocode
- for i $\gets$ 0 to k
- do C[i] $\gets$ 0
- for j $\gets$ 1 to length [A]
- do C[A[j]] $\gets$ C[A[j]] +1
- /* C[i] now contains the number of elements equal to i. */
- for i $\gets$ 1 to k
- do C[i] $\gets$ C[i] + C[i-1]
- /* C[i] now contain the number of elements less than or equal to i */
- for j $\gets$ length[A] down to 1
- do B [C[A[j]] $\gets$ A[j]
- C[A[j]] $\gets$ C[A[j]]-1
- Let Array A [1…………….n] contains input sequence where one entry in this array that is A[j] belongs { 0,1,……K} and i = 0,1,……… n where n is the largest element in the array.
- The array C [ $k_{1}……………………..k_{n}$] is used for auxiliary storage where $k_{1}$ and [ $k_{n}$ are minimum and maximum key value in the given input sequence.
- The array B [ 1…………………..n] is used to hold the sorted out.
- Each index (i) in array c used to count how many elements in A have the (i). The elements sorted in C array used to put the elements in a into their write position in the resulting array B.
- This procedure takes $\theta (k+n) $ time to run.
- The counting sort beats the lower bound $\Omega ( n log n) because it not a comparison based sorting there is no comparison between elements counting sort uses the actual values of the elements in index into an array.
Counting Sort Example Step By Step
Question: Illustrate the operation of Counting Sort on the array A=(6,0,2,0,1,3,4,6,1,3,2)
Answer:
Here K=6 (highest number in A)
For i = 0 to 6
c[i] = 0
i.e,
for j $\gets$ 1 to 11
for i =1 to 6
j | A[j] | C[A[j]] | B[C[A[j]] $\gets$ A[j] | C[A[j]]$\gets$ C[A[j]]-1 |
11 | 2 | 6 | B[6] $\gets$ 2 | C[2] $\gets$ 5 |
10 | 3 | 8 | B[8] $\gets$ 3 | C[3] $\gets$ 7 |
9 | 1 | 4 | B[4] $\gets$ 1 | C[1] $\gets$ 3 |
8 | 6 | 11 | B[11] $\gets$ 6 | C[6] $\gets$ 10 |
7 | 4 | 9 | B[9] $\gets$ 4 | C[4] $\gets$ 8 |
6 | 3 | 7 | B[7] $\gets$ 3 | C[3] $\gets$ 6 |
5 | 1 | 3 | B[3] $\gets$ 1 | C[1] $\gets$ 2 |
4 | 0 | 2 | B[2] $\gets$ 0 | C[0] $\gets$ 1 |
3 | 2 | 5 | B[5] $\gets$ 2 | C[2] $\gets$ 4 |
2 | 0 | 1 | B[1] $\gets$ 0 | C[0] $\gets$ 0 |
1 | 6 | 10 | B[10] $\gets$ 6 | C[6] $\gets$ 9 |
Thus, the final Sorted Array is B
Discover more from easytechnotes
Subscribe to get the latest posts sent to your email.