w3resource logo


C Programming Exercises

C Exercises: Counting sort algorithm

Secondary Nav

C Programming Searching and Sorting Algorithm: Exercise-9 with Solution

Write a C Program for counting sort.

Note:
According to Wikipedia "In computer science, counting sort is an algorithm for sorting a collection of objects according to keys that are small integers; that is, it is an integer sorting algorithm. It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each key value in the output sequence. Its running time is linear in the number of items and the difference between the maximum and minimum key values, so it is only suitable for direct use in situations where the variation in keys is not significantly greater than the number of items. However, it is often used as a subroutine in another sorting algorithm, radix sort, that can handle larger keys more efficiently".

Sample C Code:

#include  <stdio.h>  
  
  /*  Counting sort function  */
  void  counting_sort(int a[], int k, int n)
  {
  int i, j;
  int b[15], c[100];
  for (i = 0; i <= k; i++)
  c[i] = 0;
  for (j = 1; j <= n; j++)
  c[a[j]] = c[a[j]] + 1;
  for (i = 1; i <= k; i++)
  c[i] = c[i] + c[i-1];
  for (j = n; j >= 1; j--)
  {
  b[c[a[j]]] = a[j];
  c[a[j]] = c[a[j]] - 1;
  }
  printf("The Sorted array is : ");
  for (i = 1; i <= n; i++)
  printf("%d,", b[i]);
  }
  int  main()
  {
  int n, k = 0, a[15], i;
  printf("Input number of elements:  ");
  scanf("%d", &n);
  printf("Input the array elements one  by one: \n");
  for (i = 1; i <= n; i++)
  {
  scanf("%d", &a[i]);
  if (a[i] > k) {
  k = a[i];
  }
  }
  counting_sort(a, k, n);
  printf("\n");
  return 0;
  }

Flowchart :

Flowchart: C Programming - Counting sort

C Code Editor:

#include  <stdio.h>
 
/*  Counting sort function  */
void counting_sort(int a[], int k, int n)
{
    int i, j;
    int b[15], c[100];
    for (i = 0; i <= k; i++)
        c[i] = 0;
    for (j = 1; j <= n; j++)
        c[a[j]] = c[a[j]] + 1;
    for (i = 1; i <= k; i++)
        c[i] = c[i] + c[i-1];
    for (j = n; j >= 1; j--)
    {
        b[c[a[j]]] = a[j];
        c[a[j]] = c[a[j]] - 1;
    }
    printf("The Sorted array is : ");
    for (i = 1; i <= n; i++)
        printf("%d,", b[i]);
}
int main()
{
    int n, k = 0, a[15], i;
  printf("Input number of elements: ");
    scanf("%d", &n);
    printf("Input the array elements one by one: \n");
    for (i = 1; i <= n; i++)
    {
        scanf("%d", &a[i]);
        if (a[i] > k) {
            k = a[i];
        }
    }
    counting_sort(a, k, n);
    printf("\n");
    return 0;
}

Improve this sample solution and post your code through Disqus.



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program