1.稳定性
- 排序过程中各个关键字相对位置不变,则表示该排序算法具有稳定性。
- 冒泡、插入排序具有稳定性,选择排序不具有稳定性
- 归并排序具有稳定性,快速排序和堆排序不具有稳定性。
2.综合排序
- 数据长度比较小时(60以内)综合排序会选择复杂度比较高的插入排序(O(n2)),因为插入排序的常数项低。
- 在综合排序中基础类型数据的排序用快排:因为基本数据类型的数据相同值无差异,不用区分相同的值,所以会用快排。
- 在综合排序中引用类型数据的排序用归并排序:因为数据之间是有差异的,而归并排序是一种具有稳定性的排序。
3.不基于比较的排序
- 桶排序、计数排序、基数排序,不基于比较,与被排序样本的实际数据状况很有关系,所以实际中使用不多。
- 时间复杂度O(n),额外空间复杂度O(n)
- 稳定的排序
4.求最大差值
public class MaxGap {
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;
}
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;
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));
}
public static void main(String[] args) {
MaxGap m = new MaxGap();
int[] nums = {30, 35, 40, 70, 75, 80, 86, 90};
int result = m.maxGap(nums);
System.out.println(result);
}
}