1
嘿傢伙。我試圖在Matlab中編寫一個用於heapsort的算法。它不工作。堆正在建設好。填充排序的向量不起作用。這是代碼,謝謝!Matlab中的heapsort
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
定義「不工作」 – 2010-09-20 12:09:28