package sort;
import java.util.Arrays;
/**
* RadixSort
* 基数排序算法:
* 基数排序的总体思路就是将待排序数据拆分成多个关键字进行排序
*
*/
public class RadixSort
{
private int countStep = 0;
public void sort(int[] initData)
{
int radix = 10;//采用十进制的数字
int digit = 4;//测试数据的位数
int len = initData.length;
// 缓存数组
int[] tmp = new int[len];
// buckets用于记录待排序元素的信息
int[] buckets = new int[radix];
for (int i = 0, rate = 1; i < digit; i++)
{
// 重置count数组,开始统计下一个关键字
Arrays.fill(buckets, 0);
// 将initData中的元素完全复制到tmp数组中
for (int j=0; j<len; j++)
{
tmp[j] = initData[j];
}
// 计算每个待排序数据的子关键字
for (int j = 0; j < len; j++)
{
int subKey = (tmp[j] / rate) % radix;
buckets[subKey]++;
countStep ++;
}
for (int j = 1; j < radix; j++)
{
buckets[j] = buckets[j] + buckets[j - 1];
countStep ++;
}
// 按子关键字对指定的数据进行排序
for (int m = len - 1; m >= 0; m--)
{
int subKey = (tmp[m] / rate) % radix;
initData[--buckets[subKey]] = tmp[m];
countStep ++;
}
rate *= radix;
}
}
public int showStep()
{
return countStep;
}
}
基数排序算法
最新推荐文章于 2022-05-30 08:00:00 发布