clear;clc;close all
x = [4,3,1,6,7,5,2,1,5,6,7,8];
node = floor(length(x)/2);
for i = node : -1 : 1
x = heap(x, i, length(x));
end
for i = length(x) : -1 : 1
x([1,i]) = x([i,1]);
x = heap(x, 1, i-1);
end
function x = heap(x, node, sz)
left = node * 2; % 左叶子节点
right = node * 2 + 1; % 右叶子节点
max_idx = node;
if left <= sz && x(left) > x(node)
max_idx = left;
x([left, node]) = x([node, left]);
end
if right <= sz && x(right) > x(node)
max_idx = right;
x([right, node]) = x([node, right]);
end
if max_idx ~= node
x = heap(x, max_idx, sz);
end
end
感谢@Xunna老哥的指出,上面程序存在问题,等待左右孩子完成交换后,再进行搜索,会出现问题,如果左右孩子都进行了交换,那么左孩子的就被忽略,不会进行搜索过程,因此在每次完成交换后都应该马上进行子树的搜索,程序修改如下,欢迎批评指正。
clear;clc;close all
x = [4,3,1,6,7,5,2,1,5,6,7,8];
node = floor(length(x)/2);
for i = node : -1 : 1
x = heap(x, i, length(x));
end
for i = length(x) : -1 : 1
x([1,i]) = x([i,1]);
x = heap(x, 1, i-1);
end
function x = heap(x, node, sz)
left = node * 2; % 左叶子节点
right = node * 2 + 1; % 右叶子节点
if left <= sz && x(left) > x(node)
max_idx = left;
x([left, node]) = x([node, left]);
x = heap(x, max_idx, sz);
end
if right <= sz && x(right) > x(node)
max_idx = right;
x([right, node]) = x([node, right]);
x = heap(x, max_idx, sz);
end
end