Advertisement
Shailrshah

Radix Sort

Oct 4th, 2013
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.04 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. void radixsort(int *a, int n){
  4.     int i, m = a[0], exp = 1;
  5.     int *temp = (int *) malloc(sizeof(int) * n); //temp array
  6.     for(i = 1; i < n; i++) if (a[i] > m) m = a[i]; //find maximum element
  7.     while (m / exp > 0){
  8.         int digit[10] ={0}; //initialize all elements in digit[] to 0
  9.         for(i = 0; i < n; i++) digit[(a[i] / exp) % 10]++; //add 1 corresponding to index of digit
  10.         for(i = 1; i < 10; i++) digit[i] += digit[i - 1]; //keep on adding from left to right
  11.         for(i = n - 1; i >= 0; i--) temp[--digit[(a[i] / exp) % 10]] = a[i]; //put number in temp
  12.         for(i = 0; i < n; i++) a[i] = temp[i]; //copy from temp[] to a[]
  13.         exp *= 10;
  14.     }
  15. }
  16. int main(){
  17.     int i, n, *arr;
  18.     printf("Enter total elements: ");
  19.     scanf("%d", &n);
  20.     arr = (int *) malloc(sizeof(int) * n);
  21.     printf("Enter %d Elements : ", n);
  22.     for (i = 0; i < n; i++) scanf("%d", &arr[i]);
  23.     radixsort(&arr[0], n);
  24.     for(i = 0; i<n; i++) printf("%d\t", arr[i]);
  25.     return 0;
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement