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