[数据结构][Sort]Radix Sort

 1 public class Solution 
 2 {
 3     public void radixSort(int[] data) 
 4     {
 5         for (int position = 0; position <= getMaxDigit(data); position++) 
 6         {
 7             int[][] bucket = new int[data.length + 1][10];
 8 
 9             for (int i = 0; i < data.length; i++) 
10             {
11                 int col = 0;
12 
13                 if (getDigit(data[i]) >= position) 
14                 {
15                     col = (data[i] / (int) Math.pow(10, position)) % 10;
16                 }
17 
18                 int row = ++ bucket[0][col];
19 
20                 bucket[row][col] = data[i];
21             }
22 
23             for (int count = 0, col = 0; col < 10; col++) 
24             {
25                 for (int row = 1; row <= bucket[0][col]; row++) 
26                 {
27                     data[count++] = bucket[row][col];
28                 }
29             }
30         }
31     }
32 
33     public int getMaxDigit(int[] data) 
34     {
35         int result = 0;
36 
37         for (int item : data) 
38         {
39             int position = getDigit(item);
40 
41             if (position > result) 
42             {
43                 result = position;
44             }
45         }
46 
47         return result;
48     }
49 
50     public int getDigit(int data) 
51     {
52         int result = 0;
53 
54         for (int i = 10; data / i > 0; i = i * 10) 
55         {
56             result++;
57         }
58 
59         return result;
60     }
61     
62 }

 

posted @ 2017-09-04 00:15  StringBuilder  阅读(141)  评论(0)    收藏  举报