基本思想
将所有待比较的数值统一为同样的数位长度,数位较短的前面补0,然后,从最低位开始,一次进行一次排序,这样从最低位开始一直到最高位排序完成以后,数列就变成一个有序序列
Java代码实现
public class RadixSort {
public static void main(String[] args) {
int[] w=new int[8000000];
for (int i = 0; i < w.length; i++) {
w[i] = (int) (Math.random() * 80000000);
}
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String de = dateFormat.format(date);
System.out.println(de);
radixSort(w);
Date date1 = new Date();
SimpleDateFormat dateFormat1 = new SimpleDateFormat("mm:ss");
String de1 = dateFormat1.format(date1);
System.out.println(de1);
}
public static void radixSort(int[] arr) {
int[][] buckets = new int[10][arr.length];
int[] bucketElementCounts = new int[10];//定义一个数组来记录每个桶中的元素个数
int mod = 0;
int max = arr[0];
int maxLength=0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
while (max != 0) {
max = max / 10;
maxLength++;
}
System.out.println(maxLength);
for (int m=0,n=1;m<maxLength;m++,n*=10){
for (int i = 0; i < arr.length; i++) {
mod=arr[i]/n%10;
buckets[mod][bucketElementCounts[mod]] = arr[i];
bucketElementCounts[mod]++;
}
int index = 0;
//按照桶的顺序,依次把数据存入数组
for (int i = 0; i < 10; i++) {
for (int j = 0; j < bucketElementCounts[i]; j++) {
arr[index] = buckets[i][j];
index++;
}
//赋值完成后,将bucketElementCounts[i] 置为0
bucketElementCounts[i] = 0;
}
}
}
public static void radixSort2(int[] arr) {
//第一轮排序
//第一轮排序
//用二维数组来初始化10个桶,每个桶代表一个一维数组,大小为arr.length
int[][] buckets = new int[10][arr.length];
int[] bucketElementCounts = new int[10];//定义一个数组来记录每个桶中的元素个数
int mod = 0;
for (int i = 0; i < arr.length; i++) {
mod=arr[i]%10;
buckets[mod][bucketElementCounts[mod]] = arr[i];
bucketElementCounts[mod]++;
}
int index = 0;
//按照桶的顺序,依次把数据存入数组
for (int i = 0; i < 10; i++) {
for (int j = 0; j < bucketElementCounts[i]; j++) {
arr[index] = buckets[i][j];
index++;
}
//赋值完成后,将bucketElementCounts[i] 置为0
bucketElementCounts[i] = 0;
}
//******************************************//
//第二轮
for (int i = 0; i < arr.length; i++) {
mod=arr[i]/10%10;
buckets[mod][bucketElementCounts[mod]] = arr[i];
bucketElementCounts[mod]++;
}
index = 0;
//按照桶的顺序,依次把数据存入数组
for (int i = 0; i < 10; i++) {
for (int j = 0; j < bucketElementCounts[i]; j++) {
arr[index] = buckets[i][j];
index++;
}
}
}
}
运行结果