堆排序
Sunny-117 opened this issue · comments
堆排序
//nums为要排序的数组
function heapify(heap, i, len) {
let max = i
let left = 2 * i + 1
let right = 2 * i + 2
if (left < len && heap[left] > heap[max]) {
max = left
}
if (right < len && heap[right] > heap[max]) {
max = right
}
if (max !== i) {
[heap[i], heap[max]] = [heap[max], heap[i]]
heapify(heap, max, len)
}
}
//第一步 建立最大堆(升序)从最后一个非叶子节点开始
for (let i = Math.floor(nums.length / 2) - 1; i >= 0; i--) {
heapify(nums, i, nums.length)
}
//第二步 排序
for (let i = nums.length - 1; i >= 0; i--) {
[nums[0], nums[i]] = [nums[i], nums[0]]
heapify(nums, 0, i)
}
const h = [2, 3, 1, 4, 11, 22, 2, 3];
const res = [];
let size = h.length;
let m = size;
h.unshift(0);
function down(u) {
let t = u;
if (u * 2 <= size && h[u * 2] < h[t]) t = u * 2;
if (u * 2 + 1 <= size && h[u * 2 + 1] < h[t]) t = u * 2 + 1;
if (t !== u) {
[h[u], h[t]] = [h[t], h[u]];
down(t);
}
}
for (let i = Math.floor(size / 2); i; i--) down(i);
while(m--){
res.push(h[1]);
h[1] = h[size];
size--;
down(1);
}
console.log(res);