/** * 基数排序 */ @Test public void RadioSort(){ int[] array = {123,345,5555,66666,764,12,33,455}; int maxLength = maxLength(array); int[] newArray = sortCore(array,0,maxLength); System.out.println(Arrays.toString(newArray)); } public int[] sortCore(int[] array,int dig,int maxLength){ if(dig>=maxLength){ return array; } final int radix=10; int arrayLength = array.length; int[] count=new int[radix]; int[] bucket = new int[arrayLength]; for(int i=0;i<array.length;i++){ count[getDigit(array[i],dig)]++; } for (int i=1;i<radix;i++){ count[i]=count[i]+count[i-1]; } for (int i=arrayLength-1;i>=0;i--){ int num=array[i]; int d=getDigit(num,dig); bucket[count[d]-1]=num; count[d]--; } return sortCore(bucket,dig+1,maxLength); } public int maxLength(int[] array){ int maxLength = 0; for (int i=0;i<array.length;i++){ int currentLength =length(array[i]); if(maxLength<currentLength){ maxLength=currentLength; } } return maxLength; } public int length(int num){ return String.valueOf(num).length(); } public int getDigit(int x,int d){ int[] a={ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; return ((x/a[d])%10); }