radix_sort.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // radix sort implementation
  2. #include <stdio.h>
  3. // A utility function to get maximum value in arr[]
  4. int getMax(int arr[], int n){
  5. int mx = arr[0];
  6. for (int i = 1; i < n; i++)
  7. if (arr[i] > mx)
  8. mx = arr[i];
  9. return mx;
  10. }
  11. // A function to do counting sort of arr[] according to
  12. // the digit represented by exp.
  13. void countSort(int arr[], int n, int exp){
  14. int output[n]; // output array
  15. int i, count[10] = { 0 };
  16. // Store count of occurrences in count[]
  17. for (i = 0; i < n; i++)
  18. count[(arr[i] / exp) % 10]++;
  19. // Change count[i] so that count[i] now contains actual
  20. // position of this digit in output[]
  21. for (i = 1; i < 10; i++)
  22. count[i] += count[i - 1];
  23. // Build the output array
  24. for (i = n - 1; i >= 0; i--) {
  25. output[count[(arr[i] / exp) % 10] - 1] = arr[i];
  26. count[(arr[i] / exp) % 10]--;
  27. }
  28. // Copy the output array to arr[], so that arr[] now
  29. // contains sorted numbers according to current digit
  30. for (i = 0; i < n; i++)
  31. arr[i] = output[i];
  32. }
  33. void radixsort(int arr[], int n){
  34. // Find the maximum number to know number of digits
  35. int m = getMax(arr, n);
  36. // Do counting sort for every digit. Note that instead
  37. // of passing digit number, exp is passed. exp is 10^i
  38. // where i is current digit number
  39. for (int exp = 1; m / exp > 0; exp *= 10)
  40. countSort(arr, n, exp);
  41. }
  42. // A utility function to print an array
  43. void print(int arr[], int n){
  44. for (int i = 0; i < n; i++)
  45. printf("%d ", arr[i]);
  46. }
  47. // Driver Code
  48. int main()
  49. {
  50. int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 };
  51. int n = sizeof(arr) / sizeof(arr[0]);
  52. // Function Call
  53. radixsort(arr, n);
  54. print(arr, n);
  55. return 0;
  56. }