桶排序、计数排序、基数排序的介绍
1,非基于比较的排序,与被排序的样本的实际数据状况很有关系,所 以实际中并不经常使用
2,时间复杂度O(N),额外空间复杂度O(N)
3,稳定的排序
补充问题
给定一个数组,求如果排序之后,相邻两数的最大差值,要求时 间复杂度O(N),且要求不能用非基于比较的排序。
假设有n个数
1)准备n+1个桶
2)遍历n个数,找到最大值和最小值
3)如果最小值和最大值相等,最大差值是0
4)如果不相等,最小值放在0号桶,最大值放在n号桶,其他部分(最大值-最小值)/(n+1),即每个桶有属于自己的范围
5)最左边非空(有最小值),最右边也非空(有最大值),则n个数,n+1个桶必然存在一个空桶
6)每个桶记录最小值,最大值,是否有值
7)遍历桶,设置桶空的目的:最大差值一定不是来自一个桶内部
代码如下:
public static int maxGap(int[] nums) {
if (nums == null || nums.length < 2) {
return 0;
}
int len = nums.length;
//遍历数组找到最小值和最大值
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < len; i++) {
min = Math.min(min, nums[i]);
max = Math.max(max, nums[i]);
}
if (min == max) {
return 0;
}
//每个桶都含有3个参数
boolean[] hasNum = new boolean[len + 1];
int[] maxs = new int[len + 1];
int[] mins = new int[len + 1];
int bid = 0;
//这个循环表示:当前数去几号桶,修改最小值,最大值
for (int i = 0; i < len; i++) {
//确定当前数属于几号桶
bid = bucket(nums[i], len, min, max);
mins[bid] = hasNum[bid] ? Math.min(mins[bid], nums[i]) : nums[i];
maxs[bid] = hasNum[bid] ? Math.max(maxs[bid], nums[i]) : nums[i];
hasNum[bid] = true;
}
int res = 0;
int lastMax = maxs[0];
int i = 1;
//找到每个非空桶,以及距离该桶最近的左边非空桶,用当前的最小减去前一个的最大,res是全局最大
for (; i <= len; i++) {
if (hasNum[i]) {
res = Math.max(res, mins[i] - lastMax);
lastMax = maxs[i];
}
}
return res;
}
public static int bucket(long num, long len, long min, long max) {
return (int) ((num - min) * len / (max - min));
}