In this tutorial you will learn about the Radix Sort Algorithm and its application with practical example.
Radix 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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
#include<stdio.h> // Function to find largest element int largest(int a[], int n) { int large = a[0], i; for(i = 1; i < n; i++) { if(large < a[i]) large = a[i]; } return large; } // Function to perform sorting void radix_sort(int a[], int n) { int bucket[10][10], bucket_count[10]; int i, j, k, remainder, NOP=0, divisor=1, large, pass; large = largest(a, n); while(large > 0) { NOP++; large/=10; } for(pass = 0; pass < NOP; pass++) { for(i = 0; i < 10; i++) { bucket_count[i] = 0; } for(i = 0; i < n; i++) { remainder = (a[i] / divisor) % 10; bucket[remainder][bucket_count[remainder]] = a[i]; bucket_count[remainder] += 1; } i = 0; for(k = 0; k < 10; k++) { for(j = 0; j < bucket_count[k]; j++) { a[i] = bucket[k][j]; i++; } } divisor *= 10; } } int main() { int i, n, a[10]; printf("Enter number of elements: "); scanf("%d",&n); printf("Enter %d integer numbers\n", n); for(i = 0; i < n; i++) { scanf("%d",&a[i]); } radix_sort(a,n); printf("Elements after sorting: "); for(i = 0; i < n; i++) printf("%d ",a[i]); printf("\n"); return 0; } |
Output:-