| #include <stdio.h> | |
| #include <conio.h> | |
| int max_digits(int a[], int n){ | |
| int max = a[0], digits = 0, i; | |
| for(i = 1; i < n; i++){ | |
| if(a[i] > max){ | |
| max = a[i]; | |
| } | |
| } | |
| while(max > 0){ | |
| max /= 10; | |
| digits++; | |
| } | |
| return digits; | |
| } | |
| void radix_sort(int a[], int n){ | |
| int pass, i, j, k, r, div = 1, bucket[10][20], count[10]; | |
| int max = max_digits(a,n); | |
| for(pass = 1; pass <= max; pass++){ | |
| for(i = 0; i < 10; i++){ | |
| count[i] = 0; | |
| } | |
| for(i = 0; i < n; i++){ | |
| r = (a[i] / div) % 10; | |
| bucket[r][count[r]] = a[i]; | |
| count[r]++; | |
| } | |
| k = 0; | |
| for(i = 0; i < 10; i++){ | |
| for(j = 0; j < count[i]; j++){ | |
| a[k++] = bucket[i][j]; | |
| } | |
| } | |
| div *= 10; | |
| } | |
| } | |
| int main(){ | |
| int i; | |
| int a[] = {10,9,8,7,6,5,4,3,2,1,0,999,344}; | |
| int n = sizeof(a)/ sizeof(a[0]); | |
| radix_sort(a,n); | |
| printf("The sorted array is: \n"); | |
| for(i = 0; i < n; i++){ | |
| printf("%d ", a[i]); | |
| } | |
| return 0; | |
| } | |
Friday, 4 November 2016
Program 3 - Radix Sort
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment