太自由

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
 1 package cn.sun.it.review;
 2 
 3 import java.util.Arrays;
 4 
 5 public class RadixSort {
 6 
 7     public static void main(String[] args) {
 8         int[] arr = {278,109,63,930,589,184,505,269,8,83};
 9         int[] sort = sort(arr);
10         System.out.println(Arrays.toString(sort));
11     }
12 
13     public static int[] sort(int[] sourceArray) {
14         int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
15         int maxDigit = getMaxDigit(arr);
16         return radixSort(arr, maxDigit);
17     }
18 
19     private static int getMaxDigit(int[] arr) {
20         int maxValue = getMaxValue(arr);
21         return getNumLength(maxValue);
22 
23     }
24 
25     private static int getMaxValue(int[] arr) {
26         int maxValue = arr[0];
27         for (int value : arr) {
28             if (maxValue < value) {
29                 maxValue = value;
30             }
31         }
32         return maxValue;
33     }
34 
35     private static int getNumLength(long num) {
36         if (num == 0) {
37             return 1;
38         }
39         int length = 0;
40         for (long temp = num; temp != 0; temp /= 10) {
41             length++;
42         }
43         return length;
44     }
45 
46     private static int[] radixSort(int[] arr, int maxDigit) {
47         int mod = 10;
48         int dev = 1;
49         for (int i = 0; i < maxDigit; i++, dev *= 10, mod *= 10) {
50             int[][] counter = new int[mod*2][0];
51             for(int j=0;j<arr.length;j++){
52                 int bucket = ((arr[j]%mod)/dev)+mod;
53                 counter[bucket] = arrayAppend(counter[bucket],arr[j]);
54             }
55             int pos =0;
56             for(int[] bucket : counter){
57                 for(int value : bucket){
58                     arr[pos++] = value;
59                 }
60             }
61         }
62         return arr;
63     }
64 
65     private static int[] arrayAppend(int[] arr, int value) {
66         arr = Arrays.copyOf(arr, arr.length+1);
67         arr[arr.length-1] = value;
68         return arr;
69     }
70 }

 

posted on 2021-04-09 18:42  太自由  阅读(62)  评论(0)    收藏  举报