您的位置:首页 > 其它

8大排序之(五)------简单理解 基数排序 与时间复杂度

2016-08-22 19:25 232 查看
什么是基数排序?

(一)基数排序的思想:把待排序的整数按位分,分为个位,十位.....从小到大依次将位数进行排序。实际上分为两个                                           过程:分配和收集。

                                        分配就是:从个位开始,按位数从小到大把数据排好,分别放进0--9这10个桶中;

                                        收集就是:依次将0-9桶中的数据放进数组中

                                         重复这两个过程直到最高位

(二)过程:比如现在要排序  {400,31,53,72,6,29}

                         首先按个位的大小依次排序,排序结果如下:



按十位进行排序,结果如下:



按百位排序后,结果如下:



(三)代码如下:public class jishu {

public static void main(String args[]) {

int a [] = {400,31,53,72,6,29};
radixSort(a,10,3);
for(int m = 0;m < a.length;m++){
System.out.print(a[m]+",");
}
}

/**
* @param array 待排序数组
* @param radix 基数(10,盒子个数)
* @paramdistanced 待排序中,最大的位数
* */
private static void radixSort(int[] array,int radix, int distance) {
int length = array.length;
int[] temp = new int[length];//用于暂存元素
int[] count = new int[radix];//用于计数排序 盒子 每一位的个
int divide = 1;

for (int i = 0; i < distance; i++) {

System.arraycopy(array, 0,temp, 0, length);
Arrays.fill(count, 0);//盒子清空

for (int j = 0; j < length; j++) {//这个循环用来把每个数的个十百千位分开,并且使相对应号数的桶的个数增加1
//divide : 1 10 100
//radix : 基数 10
int tempKey = (temp[j]/divide) % radix; //temp[j]/divide 每一位的个
count[tempKey]++; //每一位的个
}

//radix : 基数 10
for (int j = 1; j < radix; j++) {
count [j] = count[j] + count[j-1];
}

//个人觉的运用 数排序实现计数排序的重点在下面这个方法
for (int j = length - 1; j >= 0; j--) {
int tempKey = (temp[j]/divide)%radix;
count[tempKey]--;
array[count[tempKey]] = temp[j];
}

divide = divide * radix; // 1 10 100

}

}
(四)时间复杂度
分配的时间复杂度为O(n)

收集的的时间复杂度为O(radix)

分配和收集共需要distance趟,

所以基数排序的时间复杂度为O(d(n+r))

我们可以看出,基数排序的效率和初始序列是否有序没有关联。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息