题目:堆排序 递增
思路:先构建大根堆,交换0位置和大根堆最后位置,大根堆size--,由于0位置值更新了,需要从o开始往下撸一遍,把0位置值放在正确位置
// 堆排序
public static void heapSort(int[] arr) {
if (arr == null || arr.length <= 0)
return;
// 在arr上构建大根堆
buildHeap(arr);
// 交换第一个和最后一个位置元素,小根堆长度--,同时更新小根堆
for (int i = arr.length - 1; i > 0; i--) {
swap(arr, i, 0);
down(arr, 0, i - 1);
}
}
public static void buildHeap(int[] arr) {
for (int i = arr.length - 1; i >= 0; i--) {
// 将当前i位置元素往下怼到正确的位置
down(arr, i, arr.length - 1);
}
}
// end为可以访问到的位置
public static void down(int[] arr, int index, int end) {
int child = index * 2 + 1;
int parent = index;
while (child <= end) {
child = child + 1 <= end && arr[child + 1] > arr[child] ? child + 1 : child;
if (arr[parent] > arr[child]) {
break;
}
swap(arr, parent, child);
parent = child;
child = parent * 2 + 1;
}
}
public static void swap(int[] arr, int a, int b) {
int tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
题目:已知一个几乎有序的数组。几乎有序是指,如果把数组排好顺序的话,每个元素移动的距离一定不超过k,并且k相对于数组长度来说是比较小的。
请选择一个合适的排序策略,对这个数组进行排序。
思路:维护k+1长度小根堆,遍历数组前k元素初始化小根堆,数组后续遍历同时poll栈顶元素(就是最终的正确值)
public static void sortedArrDistanceLessK(int[] arr, int k) {
if (k == 0)
return;
PriorityQueue<Integer> queue = new PriorityQueue<>();
int i = 0;
while (i <= Math.min(arr.length-1, k - 1)) {
queue.add(arr[i]);
i++;
}
int index = 0;
int[] help = new int[arr.length];
while (i<arr.length){
queue.add(arr[i]);
// 第一个位置的最小值一定在queue里面
help[index++] = queue.poll();
i++;
}
while (!queue.isEmpty()){
help[index++] = queue.poll();
}
i = 0;
while (i<arr.length){
arr[i] = help[i];
i++;
}
}