Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. // C++ implementation of Radix Sort
  2. #include<iostream>
  3. using namespace std;
  4.  
  5. // A utility function to get maximum value in arr[]
  6. int getMax(int arr[], int n)
  7. {
  8. int mx = arr[0];
  9. for (int i = 1; i < n; i++)
  10. if (arr[i] > mx)
  11. mx = arr[i];
  12. return mx;
  13. }
  14.  
  15. // A function to do counting sort of arr[] according to
  16. // the digit represented by exp.
  17. void countSort(int arr[], int n, int exp)
  18. {
  19. int output[n]; // output array
  20. int i, count[10] = {0};
  21.  
  22. // Store count of occurrences in count[]
  23. for (i = 0; i < n; i++)
  24. count[ (arr[i]/exp)%10 ]++;
  25.  
  26. // Change count[i] so that count[i] now contains actual
  27. // position of this digit in output[]
  28. for (i = 1; i < 10; i++)
  29. count[i] += count[i - 1];
  30.  
  31. // Build the output array
  32. for (i = n - 1; i >= 0; i--)
  33. {
  34. output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
  35. count[ (arr[i]/exp)%10 ]--;
  36. }
  37.  
  38. // Copy the output array to arr[], so that arr[] now
  39. // contains sorted numbers according to current digit
  40. for (i = 0; i < n; i++)
  41. arr[i] = output[i];
  42. }
  43.  
  44. // The main function to that sorts arr[] of size n using
  45. // Radix Sort
  46. void radixsort(int arr[], int n)
  47. {
  48. // Find the maximum number to know number of digits
  49. int m = getMax(arr, n);
  50.  
  51. // Do counting sort for every digit. Note that instead
  52. // of passing digit number, exp is passed. exp is 10^i
  53. // where i is current digit number
  54. for (int exp = 1; m/exp > 0; exp *= 10)
  55. countSort(arr, n, exp);
  56. }
  57.  
  58. // A utility function to print an array
  59. void print(int arr[], int n)
  60. {
  61. for (int i = 0; i < n; i++)
  62. cout << arr[i] << " ";
  63. }
  64.  
  65. // Driver program to test above functions
  66. int main()
  67. {
  68. int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
  69. int n = sizeof(arr)/sizeof(arr[0]);
  70. radixsort(arr, n);
  71. print(arr, n);
  72. return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement