|
| 1 | +package com.openmind.sort; |
| 2 | + |
| 3 | +/** |
| 4 | + * Shell Sort: ascending , Diminishing Increment Sort |
| 5 | + * U complexity: O(n^(1.3—2)) |
| 6 | + * Mem complexity: O(1) |
| 7 | + * Unstable |
| 8 | + */ |
| 9 | +public class RadixSort extends BaseSortProcess { |
| 10 | + |
| 11 | + @Override |
| 12 | + protected int[] sort(int[] a) { |
| 13 | + int max = getMax(a); |
| 14 | + for (int exp = 1; max / exp > 0; exp *= 10) { |
| 15 | + countSort(a, a.length, exp); |
| 16 | + } |
| 17 | + |
| 18 | + return a; |
| 19 | + } |
| 20 | + |
| 21 | + private void countSort(int[] a, int n, int exp) { |
| 22 | + |
| 23 | + int[] count = new int[10]; |
| 24 | +// Arrays.fill(count, 0); |
| 25 | + |
| 26 | + int t; |
| 27 | + for (int i = 0; i < n; i++) { |
| 28 | + t = (a[i] / exp) % 10; |
| 29 | + count[t]++; |
| 30 | + } |
| 31 | + |
| 32 | + //count[i], total count of a(0,1,...,i ) |
| 33 | + for (int i = 1; i < 10; i++) { |
| 34 | + count[i] += count[i - 1]; |
| 35 | + } |
| 36 | + |
| 37 | + int[] output = new int[n]; |
| 38 | + for (int i = n - 1; i >= 0; i--) { |
| 39 | +// for (int i = 0; i < n; i++) { |
| 40 | + t = (a[i] / exp) % 10; |
| 41 | + //indices is 1 less than count |
| 42 | + output[count[t] - 1] = a[i]; |
| 43 | + count[t]--; |
| 44 | + } |
| 45 | + |
| 46 | + for (int i = 0; i < n; i++) { |
| 47 | + a[i] = output[i]; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + private int getMax(int[] a) { |
| 52 | + int n = a.length, max = a[0]; |
| 53 | + for (int i = 1; i < n; i++) { |
| 54 | + if (a[i] > max) { |
| 55 | + max = a[i]; |
| 56 | + } |
| 57 | + } |
| 58 | + return max; |
| 59 | + } |
| 60 | + |
| 61 | + public static void main(String[] args) { |
| 62 | + new RadixSort().proceeding(10); |
| 63 | + } |
| 64 | +} |
0 commit comments