基数排序是一种非比较排序,它属于分配式排序(distribution sort)。基数排序是一种高效的排序算法,它可以突破比较类排序算法的极限(nlogn),其时间复杂度可以表示为O(Kn)。其中n就是待排序序列的元素个数,K是数字的位数。
1. 算法思想
算法思想是这样的,说白就是先排序个位,在排序十位…如图中数组,
1.首先确定排序次数:最大值几位数就要排序几次,图中数组最大值为345需要排序3次。
2.先把数组按照个位数大小排序:可以看到242和192 个位数一样大,按照顺序用一个链表把192 接在242下面,135 和345也是如此,(如图中收集个位)。排序好后,整合成一个数组a(收集个位下面的数组)。
3.再把数组a按照十位数大小排序,方法和排个位的一样(如图收集十位),然后整个成数组a(如图收集十位下面的数组)
4.最后百位排序,也如图所示,方法和个位十位排序与一样,此次再整合成数组a,a就是排序好的数组。
2.代码实现
public class radixSorting {
public void radixsorting(int[] a) {
/*
1. 基数排序中排序次数
*/
int max = 0;
for(int i = 0;i < a.length;i ++) {
//最大值
if (max < a[i]) max = a[i];
}
//获取最大值位数
int times = 0;
while(max > 0) {
max = max/10;
times ++;
}
/*
2. 初始化数组
*/
//二维数组用来存数据
List<ArrayList> queue = new ArrayList<>();
//初始化二维数组
for(int i = 0;i < 10;i ++) {
ArrayList q = new ArrayList<>();
queue.add(q);
}
/*
3.开始排序
*/
for(int i = 0; i < times;i ++) {
for(int j = 0;j < a.length;j ++) {
//i = 0取个位数 ,i = 1取是为, i = 2 取百位
int x = a[j]%(int)Math.pow(10, i + 1)/(int)Math.pow(10, i);
//添加数据操作
ArrayList q = queue.get(x);
q.add(a[j]);
queue.set(x, q);
}
/*
4. 把二维数组塞到数组中
*/
int count = 0;
for(int j = 0;j < 10;j ++) {
while(queue.get(j).size()>0) {
ArrayList<Integer> qArrayList = queue.get(j);
a[count] = qArrayList.get(0);
qArrayList.remove(0);
count ++;
}
}
}
}
}
3.一个问题
基数排序算法效率比快速排序高,为什么没有快速排序算法流行呢??
算法导论有相关的说明: