自己做了一个关于堆的程序,输入方法如下:读入一个n,代表结点个数,然后依次读入n个结点,再然后读入1或2或3或4:1代表删除一个结点,然后你要读入要删除的结点;2代表删除首结点;3代表插入一个新节点,然后你需要读入要插入的结点;4代表对堆进行排序。
maxn=100;
arr=array[1..maxn]of longint;
h:arr;
n,p,q,x:longint;
var
done:boolean;
t:longint;
begin
if i=1 then exit;
repeat
done:=false;
if h[i]>h[i div 2] then begin t:=h[i]; h[i]:=h[i div 2]; h[i div 2]:=t; end
else done:=true;
i:=i div 2;
until (i=1) or done;
var
done:boolean;
t:longint;
begin
done:=false;
if 2*i>n then exit;
repeat
i:=2*i;
if (i+1<=n) and (h[i+1]>h[i]) then inc(i);
if h[i div 2]
else done:=true;
until (2*i>n) or done;
begin
inc(n);
h[n]:=x;
siftup(h,n);
var
x,y:longint;
begin
x:=h[i];
y:=h[n];
dec(n);
if i=n+1 then exit;
h[i]:=y;
if y<=x then siftup(h,i)
else siftdown(h,n,i);
begin
x:=h[1];
heapdelete(h,n,1);
var
i:longint;
begin
for i:=n div 2 downto 1 do
siftdown(h,n,i);
var
j,t:longint;
begin
for j:=n downto 2 do
begin
t:=h[1];
h[1]:=h[j];
h[j]:=t;
siftdown(h,j-1,1);
write(h[j],' ');
end;
write(h[1]);
var
i:longint;
begin
readln(n);
for i:=1 to n do
read(h[i]);
var
i:longint;
begin
writeln;
for i:=1 to n do
write(h[i],' ');
heapinput;
makeheap(h,n);
heapprint(h,n);
readln(p);
case p of
1:begin
writeln('delete i');
readln(q);
heapdelete(h,n,q);
heapprint(h,n);
end;
2:begin
writeln('return max');
heapdeletemax(h,n,x);
writeln(x);
heapprint(h,n);
end;
3:begin
writeln('insert x');
readln(x);
heapinsert(h,n,x);
heapprint(h,n);
end;
4:begin
writeln('heap sort');
heapsort(h,n);
end;
end;
程序:
const
type
var
procedure siftup(var lr:arr;i:longint);
end;
procedure siftdown(var h:arr;n,i:longint);
end;
procedure heapinsert(var h:arr; var n:longint;x:longint);
end;
procedure heapdelete(var h:arr; var n:longint; i:longint);
end;
procedure heapdeletemax(var h:arr; var n,x:longint);
end;
procedure makeheap(var h:arr;n:longint);
end;
procedure heapsort(var h:arr;n:longint);
end;
procedure heapinput;
end;
procedure heapprint(h:arr;n:longint);
end;
begin
end.