基本思想:将所有待比较数值(正整数)统一为同样的数位长度,数位较短的数前面补零。然后,从最低位开始,依次进行一次排序。这样从最低位排序一直到最高位排序完成以后,数列就变成一个有序序列。
public class RadixSort {
public int[] radixSort(int[] data) {
int max = data[0];
for (int i = 1; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
int time = 0;
while (max > 0) {
max /= 10;
time++;
}
// 设定10个list保存数据
List<ArrayList<Integer>> queue = new ArrayList<ArrayList<Integer>>();
for (int j = 0; j < 10; j++) {
ArrayList<Integer> dataQueue = new ArrayList<Integer>();
queue.add(dataQueue);
}
// 开始进行排序
for (int i = 0; i < time; i++) {
for (int j = 0; j < data.length; j++) {
// 取到当前这个数的对应位置上的一位数
int x = data[j] % (int) Math.pow(10, i + 1)
/ (int) Math.pow(10, i);
ArrayList<Integer> returnQueue = queue.get(x);
returnQueue.add(data[j]);
queue.set(x, returnQueue);
}
int count = 0;
for (int k = 0; k < 10; k++) {
while (queue.get(k).size() > 0) {
ArrayList<Integer> tempQueue = queue.get(k);
data[count] = tempQueue.get(0);
tempQueue.remove(0);
count++;
}
}
}
return data;
}
public static void main(String args[]) {
int a[] = { 10,9,8,7,6,5,4,3,2,1};
int[] result = new RadixSort().radixSort(a);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
}
}