Radix.java 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Radix sort Java implementation
  2. // https://geeksforgeeks.org/radix-sort/
  3. import java.io.*;
  4. import java.util.*;
  5. class Radix {
  6. // A utility function to get maximum value in arr[]
  7. static int getMax(int arr[], int n)
  8. {
  9. int mx = arr[0];
  10. for (int i = 1; i < n; i++)
  11. if (arr[i] > mx)
  12. mx = arr[i];
  13. return mx;
  14. }
  15. // A function to do counting sort of arr[] according to
  16. // the digit represented by exp.
  17. static void countSort(int arr[], int n, int exp)
  18. {
  19. int output[] = new int[n]; // output array
  20. int i;
  21. int count[] = new int[10];
  22. Arrays.fill(count, 0);
  23. // Store count of occurrences in count[]
  24. for (i = 0; i < n; i++)
  25. count[(arr[i] / exp) % 10]++;
  26. // Change count[i] so that count[i] now contains
  27. // actual position of this digit in output[]
  28. for (i = 1; i < 10; i++)
  29. count[i] += count[i - 1];
  30. // Build the output array
  31. for (i = n - 1; i >= 0; i--) {
  32. output[count[(arr[i] / exp) % 10] - 1] = arr[i];
  33. count[(arr[i] / exp) % 10]--;
  34. }
  35. // Copy the output array to arr[], so that arr[] now
  36. // contains sorted numbers according to current
  37. // digit
  38. for (i = 0; i < n; i++)
  39. arr[i] = output[i];
  40. }
  41. // The main function to that sorts arr[] of
  42. // size n using Radix Sort
  43. static void radixsort(int arr[], int n)
  44. {
  45. // Find the maximum number to know number of digits
  46. int m = getMax(arr, n);
  47. // Do counting sort for every digit. Note that
  48. // instead of passing digit number, exp is passed.
  49. // exp is 10^i where i is current digit number
  50. for (int exp = 1; m / exp > 0; exp *= 10)
  51. countSort(arr, n, exp);
  52. }
  53. // A utility function to print an array
  54. static void print(int arr[], int n)
  55. {
  56. for (int i = 0; i < n; i++)
  57. System.out.print(arr[i] + " ");
  58. }
  59. // Main driver method
  60. public static void main(String[] args)
  61. {
  62. int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 };
  63. int n = arr.length;
  64. // Function Call
  65. radixsort(arr, n);
  66. print(arr, n);
  67. }
  68. }