Counting Sort in C

Here you will learn about counting sort in C

 

Counting sort algorithm is a sorting algorithm which do not involve comparison between elements of an array. In this tutorial I am sharing counting sort program in C. Steps that I am doing to sort the elements are given below.

1. First of all I am reading n elements in array a[]. While reading the array elements I have also calculated the maximum element.

2. Now the actual sorting is done in counting_sort() function. Here I am counting the occurrence of each element in the array a[] and then storing it at the index equal to the value of that element. For example occurrence of element 5 will be stored at index 5, occurrence of element 9 will be stored at index 9 and so on.

3. As the value at each index in count[] array is the occurrence of that index or element, so the elements are printed in ascending order by printing each index number of times equal to its corresponding value.

Also Read: Merge Sort in C

Counting Sort Algorithm, Counting Sort Program in C, Counting Sort Example
Counting Sort Example – Image Source

I have also added a video tutorial below that will help you to understand the counting sort algorithm easily. If you are facing any problem then ask it in the comment section.

Program for Counting Sort in C

#include<stdio.h>

void counting_sort(int a[],int n,int max)
{
     int count[50]={0},i,j;
     
     for(i=0;i<n;++i)
      count[a[i]]=count[a[i]]+1;
      
     printf("\nSorted elements are:");
     
     for(i=0;i<=max;++i)
      for(j=1;j<=count[i];++j)
       printf("%d ",i);
}

int main()
{
    int a[50],n,i,max=0;
    printf("Enter number of elements:");
    scanf("%d",&n);
    printf("\nEnter elements:");
                  
    for(i=0;i<n;++i)
    {
     scanf("%d",&a[i]);
     if(a[i]>max)
      max=a[i];
    }
     
    counting_sort(a,n,max);
    return 0;
}

 

Output

Counting Sort Algorithm, Counting Sort Program in C, Counting Sort Example
If you found any mistake or anything missing in above tutorial for counting sort in C then please mention it by commenting below.

12 thoughts on “Counting Sort in C”

  1. Hei! Thanks for the code! It was very useful for me 🙂 I really appreciate that it is clean and very easy to understand.
    though, I found a verry, verry little mistake here and i thought you might want to correct it 😀
    printf(“nEnter elements:”); needs a “\”
    Thanks again and good luck with what you are doing here 🙂

  2. Thanks for the post.
    However, I wonder this approach gives a ‘Stable sorting’, which is a characteristic of Counting Sort, as it does not actually sort by keys + pointers to records, does it?

    1. Hasan Shahriar Boni

      good program. but it is not working for the number 50 and above. this can be solved by increasing the value of the count array..

Leave a Comment

Your email address will not be published. Required fields are marked *