几乎有序的数组排序


import java.util.PriorityQueue;

/**
* 已知一个几乎有序的数组,如果排好序,每个元素的移动距离不超过k,并且k相对于数组长度是比较小的。
* 选择一种合适的算法
*/
public class SortArrayDistanceLessK {

public static void sortArrayDistanceLessK(int[] arr, int k) {
// 非法或者已知排好序
if (k == 0) {
return;
}
// 默认 小根堆/最小堆
PriorityQueue<Integer> heap = new PriorityQueue();
// 先把前面k个数加入堆,已知排好序的第一个节点必然在前面k个数中
int index = 0;
while (index <= Math.min(arr.length - 1, k - 1)) {
heap.add(arr[index++]);
}
// 从堆中弹出最小值,依次放入数组,则最终结果就是排好序的 小根堆/最小堆
int i = 0;
for (; i < arr.length; i++, index++) {
arr[i] = heap.poll();
heap.add(arr[index]);
}
while (!heap.isEmpty()) {
arr[i++] = heap.poll();
}
}

}

/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
原文地址:https://www.cnblogs.com/laydown/p/12819624.html