Counting Sort in Data Structure

  • 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

  1. for i $\gets$ 0 to k
  2. do C[i] $\gets$ 0
  3. for j $\gets$ 1 to length [A]
  4. do C[A[j]] $\gets$ C[A[j]] +1
  5. /* C[i] now contains the number of elements equal to i. */
  6. for i $\gets$ 1 to k
  7. do C[i] $\gets$ C[i] + C[i-1]
  8. /* C[i] now contain the number of elements less than or equal to i */
  9. for j $\gets$ length[A] down to 1
  10. do B [C[A[j]] $\gets$ A[j]
  11. 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:

Counting Sort

Here K=6 (highest number in A)

For i = 0 to 6

c[i] = 0

i.e,

Counting Sort

for j $\gets$ 1 to 11

for i =1 to 6

jA[j]C[A[j]]B[C[A[j]] $\gets$ A[j]C[A[j]]$\gets$ C[A[j]]-1
1126B[6] $\gets$ 2C[2] $\gets$ 5
1038B[8] $\gets$ 3C[3] $\gets$ 7
914B[4] $\gets$ 1C[1] $\gets$ 3
8611B[11] $\gets$ 6C[6] $\gets$ 10
749B[9] $\gets$ 4C[4] $\gets$ 8
637B[7] $\gets$ 3C[3] $\gets$ 6
513B[3] $\gets$ 1C[1] $\gets$ 2
402B[2] $\gets$ 0C[0] $\gets$ 1
325B[5] $\gets$ 2C[2] $\gets$ 4
201B[1] $\gets$ 0C[0] $\gets$ 0
1610B[10] $\gets$ 6C[6] $\gets$ 9

Thus, the final Sorted Array is B


Discover more from easytechnotes

Subscribe to get the latest posts sent to your email.

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Scroll to Top