Matlab中的堆排序
嘿伙计们。我正在尝试在 Matlab 中编写堆排序算法。它不起作用。堆构建良好。填充排序向量不起作用。这是代码,谢谢!
function [xs,h]= heap(x)
N = length(x);
h = zeros(1,N);
N_h = 0;
for i=1:N
N_h = N_h +1;
child = N_h;
h(child) = x(i);
while child>1
parent = floor(child/2);
if h(child)>h(parent)
tmp = h(parent);
h(parent) = h(child);
h(child) = tmp;
child = parent;
else
break
end
end
end
xs = zeros(1,N);
parent = 1;
for i = N:-1:1
xs(i) = h(1);
h(1) = h(i);
child1 = 2*parent;
child2= 2*parent+1;
if child1 <= i-1
if h(child1)>h(child2)
cchild = child1;
else
cchild = child2;
end
if h(parent) < h(cchild)
tmp = h(parent);
h(parent) = h(child);
h(child) = tmp;
parent = child;
else
break
end
end
end
Hey guys. Im trying to write an algorithm for heapsort in Matlab. Its not working. The heap is constructing fine. Filling the sorted vector is not working. Here is the code and thank you!
function [xs,h]= heap(x)
N = length(x);
h = zeros(1,N);
N_h = 0;
for i=1:N
N_h = N_h +1;
child = N_h;
h(child) = x(i);
while child>1
parent = floor(child/2);
if h(child)>h(parent)
tmp = h(parent);
h(parent) = h(child);
h(child) = tmp;
child = parent;
else
break
end
end
end
xs = zeros(1,N);
parent = 1;
for i = N:-1:1
xs(i) = h(1);
h(1) = h(i);
child1 = 2*parent;
child2= 2*parent+1;
if child1 <= i-1
if h(child1)>h(child2)
cchild = child1;
else
cchild = child2;
end
if h(parent) < h(cchild)
tmp = h(parent);
h(parent) = h(child);
h(child) = tmp;
parent = child;
else
break
end
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的 extract-first-item 代码是错误的(你可能猜到了,因为它不起作用:-))——看起来你只做了你需要的循环的一个步骤。您需要用堆的“最后一个”元素替换树的根(您正在这样做),然后从那里沿着树向下移动到修复堆属性的叶子(您只做了以下一步)那)。
另外,您正在堆弹出循环之外初始化“parent”;除非我完全误解你想要做什么,否则每次提取元素时你都希望将其重置为 1 。
Your extract-first-item code is wrong (you probably guessed that since it's the bit that isn't working :-)) -- it looks like you're doing only one step of the loop you need. You need to replace the root of the tree with the "last" element of the heap (you're doing that) and then travel down the tree from there to the leaf fixing up the heap property (you're only doing one step of that).
Also, you're initializing "parent" outside the heap-popping loop; unless I'm entirely misunderstanding what you're trying to do, you want to be resetting it to 1 every time you extract an element.