基數排序是另一種比較有特點的排序方式,它不須要直接對元素進行相互比較,也不須要將元素相互交換,你須要作的就是對元素進行「分類」。它是怎麼排序的呢?java
1 public class BaseSort { 2 public static void main(String[] args) { 3 int[] a = {13,25,1111,232,4454,79,86,98,61,447}; 4 System.out.println("初始值:"); 5 print(a); 6 a=sort(a); 7 System.out.println("\n排序後:"); 8 print(a); 9 } 10 11 12 public static int[] sort(int[] data){ 13 int maxLength = getMaxLength(data); 14 int[] tmp = baseSort(data,0,maxLength); 15 return tmp; 16 } 17 18 /** 19 * @param data 20 * @param i 21 * @param maxLength 22 * @return 23 */ 24 private static int[] baseSort(int[] data, int i, int maxLength) { 25 if(i>=maxLength){ 26 return data; 27 } 28 int len = data.length; 29 30 //建立10個桶,每一個桶中分別用來存放第i位爲0~9得數子個數 31 //例如i=0,count[1],就用來存放各位爲1得數字個數 32 int[] count = new int[10]; 33 //用來複制數組,輔助排序 34 int[] tmp = new int[len]; 35 36 //將數組中全部得數按照規則放入同種 37 for (int j = 0; j < tmp.length; j++) { 38 count[getNum(data[j], i)]++; 39 } 40 41 //將count[]數字表明桶中數字得個數,變爲下標 42 //例如:count[0]原來爲1個,count[1]爲1個,那麼count[1]後面一位得下表就是count[0]+count[1]=2 43 for (int j = 1; j < count.length; j++) { 44 count[j] = count[j-1]+count[j]; 45 } 46 //將原數組總元素按照順序複製到新數組中 47 for (int j = tmp.length-1; j >= 0; j--) { 48 int number = data[j]; 49 int a = getNum(number, i); 50 tmp[count[a]-1]=number; 51 count[a]--; 52 } 53 return baseSort(tmp, i+1, maxLength); 54 } 55 56 57 /** 58 * 獲取一個數字第i位得數字,個位從0開始 59 * @param num 60 * @param i 61 * @return 62 */ 63 private static int getNum(int num,int i){ 64 for (int j = 0; j < i+1; j++) { 65 if(j==i){ 66 num%=10; 67 }else{ 68 num=num/10; 69 } 70 } 71 return num; 72 } 73 74 /** 75 * 獲取數組得長度 76 * @param num 77 * @return 78 */ 79 private static int length(int num){ 80 return String.valueOf(num).length(); 81 } 82 83 /** 84 * 查找數組總全部得元素擁有得最大長度 85 * @param data 86 * @return 87 */ 88 private static int getMaxLength(int[] data){ 89 int maxLength = 0 ; 90 for (int i = 0; i < data.length; i++) { 91 if(maxLength<length(data[i])){ 92 maxLength = length(data[i]); 93 } 94 } 95 return maxLength; 96 } 97 98 private static void print(int[] a){ 99 for (int i = 0; i < a.length; i++) { 100 System.out.print(a[i]+" "); 101 } 102 System.out.println(); 103 } 104 }