Counting Sort | Pseudo Code | Example | Analyzing Complexity

Till now we have introduced insertion sort, merge sort, heap sort and quick sort. Out of which we know that merge sort and heap sort has a worst case of O(n*lgn) and quick sort has an average case of O(n*lgn).
Till now all the above algorithms mentioned use comparison as a medium to arrange elements in ascending or descending order. Now we are going to work on a very interesting algorithm which does not uses comparison as a medium to sort the numbers. It’s called counting sort. For a n sequence of numbers it runs in omega(n*lgn) time. Counting sort sorts the element in linear time. In this blog post we are going to- Write a pseudocode for counting sort
- Explain it via example
- Analyze the complexity of the algorithm and write a c++ program for the same.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CountingSort(A) | |
largestElementOfA = maxElement(A) | |
Let C be the auxiliary array having C[0..largestElementOfA] | |
Let B be the final sorted array having same size as that of A | |
for i = 0 to largestElementOfA | |
C[i] = 0 | |
for j = 1 to A.length | |
C[A[j]] = C[A[j]] + 1 | |
for k = 1 to largestElementOfA | |
C[A[k]] = C[A[k]] + C[A[k-1]]; | |
for n = 1 to A.length | |
B[C[A[n]]] = A[n] | |
C[A[n]] = C[A[n]] - 1 |
