基数排序必须依赖另外的排序方法,最适合的是桶式排序。
基本思路:就是将待排序的数据拆分成多个排序关键字
采用最低位优先法
依次按照数据的拆分出来的个位、十位、百位。。。的子关键字排序。
实现代码
public class MultiKeyRadixSort
{
public static void main(String[] args)
{
int[] data =
{ 1100, 192, 221, 12, 13 };
System.out.println("排序之前:\n" + Arrays.toString(data));
radixSort(data, 10, 4);
System.out.println("排序之后:\n" + Arrays.toString(data));
}
public static void radixSort(int[] data, int radix, int d)
{
int arrayLength = data.length;
// 临时数组
int[] tmp = new int[arrayLength];
// 桶式排序必须的数组
int[] buckets = new int[radix];
// 依次从最高位关键字对待排序数列排序
// rate用于保存当前计算的位
for (int i = 0, rate = 1; i < d; i++)
{
// 重置count数组
Arrays.fill(buckets, 0);
// 将data赋值到临时数组
System.arraycopy(data, 0, tmp, 0, arrayLength);
// 计算每个待排序的子关键字
for (int j = 0; j < arrayLength; j++)
{
// 计算指定位上的子关键字
int subKey = (tmp[j] / rate) % radix;
buckets[subKey]++;
}
for (int j = 1; j < radix; j++)
{
buckets[j] = buckets[j] + buckets[j - 1];
}
// 按关键字对指定数据进行排序
for (int m = arrayLength - 1; m >= 0; m--)
{
int subKey = (tmp[m] / rate) % radix;
data[--buckets[subKey]] = tmp[m];
}
System.out.println("对" + rate + "位上的子关键字排序:"
+ Arrays.toString(data));
rate *= radix;
}
}
}