In this tutorial you will learn about the Counting Sort Algorithm and its application with practical example.
Counting Sort Program In C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
#include <stdio.h> 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("Elements after sorting: "); for (i = 1; i <= n; i++) printf("%d ", B[i]); } int main() { int n, k = 0, A[15], i; printf("Enter number of elements: "); scanf("%d",&n); printf("Enter %d integer numbers\n", 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; } |
Output:-
Table Of Contents−