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.
Here is the source code of the C program to sort integers using Counting Sort technique. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program for counting sort
*/
#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]);
}
/* End of counting_sort() */
/* The main() begins */
int main()
{
int n, k = 0, A[15], i;
printf("Enter the number of input : ");
scanf("%d", &n);
printf("\nEnter the elements to be sorted :\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;
}
$ gcc countsort.c -o countsort $ ./countsort Enter the number of elements : 10 Enter the elements to be sorted : 8 11 34 2 1 5 4 9 6 47 The Sorted array is : 1 2 4 5 6 8 9 11 34 47
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
- Apply for C Internship
- Practice BCA MCQs
- Practice Computer Science MCQs
- Check Computer Science Books
- Apply for Computer Science Internship