-
-
Notifications
You must be signed in to change notification settings - Fork 229
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
堆排序 #198
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: