上面的程序有错。 记住堆排序的数组从1开始。
具体程序EMail给你了。
procedure THeapSort.Sort(var A: array of Integer);
var I, Lo, N: Integer;
procedure HeapSwap(AI, AJ: Integer);
var T: Integer;
begin
T:=A[AI];
A[AI]:=A[AJ];
A[AJ]:=T;
VisualSwap(A[AI], A[AJ], AJ, AI);
end;
procedure PushDown(First, Last: Integer);
var R, R2, R21, AR, AR2, AR21: Integer;
begin
R:=First;
while R<=(Last div 2)
do begin
R2:=R+R;
R21:=R2+1;
AR:=A[R];
AR2:=A[R2];
AR21:=A[R21];
if R=Last div 2
then begin
if AR<AR2 then HeapSwap(R, R2);
R:=Last;
end
else if (AR<AR2)and(AR2>=AR21)
then begin
HeapSwap(R, R2);
R:=R2;
end
else if (AR<AR21)and(AR21>=AR2)
then begin
HeapSwap(R, R21);
R:=R21;
end
else R:=Last;
end;
if Terminated then Exit;
end;
begin
Lo:=Low(A);
N:=High(A)-Lo+1;
for I:=(N div 2)+Lo downto Lo do PushDown(I, N+Lo);
for I:=N+Lo downto 2
do begin
HeapSwap(Lo, I);
PushDown(Lo, I-1);
// VisualSwap(A[Lo], A[I-1], Lo, I-1);
end;
end;