Sunteți pe pagina 1din 2

#include "stdio.h" #include<conio.

h> void radix_sort(int *a, int n) { int i, b[10], m = 0, exp = 1; for (i = 0; i < n; i++) { if (a[i] > m) m = a[i]; //m gives the maximum number in array }

while (m / exp > 0) { int box[10] = { 0 }; for (i = 0; i < n; i++) box[a[i] / exp % 10]++; /* a[i]/exp%10 gives unit place and is suppose a[i]/exp%10=2 then box[a[i] / exp % 10] tells number linked at box[2], i.e. how many numbers are there with unit digit 2. box[a[i] / exp % 10]++ means now u get one more number of same unit digit.*/

for (i = 1; i < 10; i++) box[i] += box[i - 1]; /* box[i] i.e. box[2] says total numbers with unit digit 2 box[i] += box[i - 1]; let box[i] stores total numbers upto box i like box[1] has num in box[0]+box[1] and box[4] has tot num in b0x[0] +box[1]+box[2]+box[3]+box[4]*/ for (i = n - 1; i >= 0; i--) b[--box[a[i] / exp % 10]] = a[i]; /* b[] is new sorted array which will store sorted values

for (i = 0; i < n; i++) a[i] = b[i]; /*now the array has changed to array sorted by unit digit same process will be done and then array has changed to array sorted by tens digit and so on */ exp *= 10; //now exp would be 10 than 100 than 1000 and so on

printf("\n\nPASS : "); for (i = 0; i < n; i++) printf("%d\t", a[i]); }//end of while }//end of radix function

void main() { int arr[10]; int i, num; printf("\nEnter total elements less than 10\n"); scanf("%d", &num); printf("\nEnter %d Elements : ", num); for (i = 0; i < num; i++) scanf("%d", &arr[i]); printf("\nARRAY : "); for (i = 0; i < num; i++) printf("%d\t", arr[i]); radix_sort(&arr[0], num); printf("\n\nSORTED ARRAY : "); for (i = 0; i < num; i++) printf("%d\t", arr[i]); getch(); }

S-ar putea să vă placă și