16120

Radix sort

May 8th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class radix {
  4.     public static void main(String[] args) {
  5.         int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 };
  6.         int n = arr.length;
  7.         radixsort(arr, n);
  8.         print(arr, n);
  9.     }
  10.  
  11.     static int getMax(int arr[], int n) {
  12.         int mx = arr[0];
  13.         for (int i = 1; i < n; i++)
  14.             if (arr[i] > mx)
  15.                 mx = arr[i];
  16.         return mx;
  17.     }
  18.  
  19.     static void countSort(int arr[], int n, int exp) {
  20.         int output[] = new int[n]; // output array
  21.         int i;
  22.         int count[] = new int[10];
  23.         Arrays.fill(count, 0);
  24.  
  25.         for (i = 0; i < n; i++)
  26.             count[(arr[i] / exp) % 10]++;
  27.  
  28.         for (i = 1; i < 10; i++)
  29.             count[i] += count[i - 1];
  30.  
  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.  
  36.         for (i = 0; i < n; i++)
  37.             arr[i] = output[i];
  38.     }
  39.  
  40.     static void radixsort(int arr[], int n) {
  41.         int m = getMax(arr, n);
  42.         for (int exp = 1; m / exp > 0; exp *= 10)
  43.             countSort(arr, n, exp);
  44.     }
  45.  
  46.     static void print(int arr[], int n) {
  47.         for (int i = 0; i < n; i++)
  48.             System.out.print(arr[i] + " ");
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment