MATLAB实现堆排序

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值