原理:首先,將所有的數值按個位數劃分到0-9個桶裏面,將桶中的數值倒出,然後按十位數劃分到0-9個桶中,然後倒出,依次類推,到最高位爲止。
import java.util.*;
public class RadixSort {
public int[] radixSort(int[] A, int n) {
// write code here基數排序
if(A ==null || n<2)
return null;
int a =1;//除數,分離出關鍵字的各個整數位
int m=1;//指向的位數
int k=0;// 最後輸出的結果
//高維表示0-9個桶,低維表示每個關鍵字各個位上的餘數,每個桶內可能有n個值
int [][] number = new int [10][n];
//創建一個數組表示number數組的每一個桶裏面的數目,
int [] count = new int [10];
while(m<=4){
for(int j=0;j<A.length;j++){
int lsd = ((A[j]/a)%10);//得到餘數
number[lsd][count[lsd]] =A[j];
count[lsd]++;//餘數爲lsd,在哪個桶內也確定,因此將桶內的數目自加
}
for(int p=0;p<10;p++){
//將桶內的值取出,重新放入到數組中
if(count[p] !=0){//判斷在哪個桶內的並且在該桶內的關鍵字的個數不爲0
for(int q=0;q< count[p];q++){
A[k] = number[p][q];
k++;
}
}
count[p]=0;
}
k=0;
a*=10;
m++;
}
return A;
}
}