Chapter 6: Heapsort
Chapter 6: Heapsort
Overview
In this chapter, we introduce another sorting algorithm. Like merge sort, but unlike insertion sort, heapsort's running time is O(n lg n). Like insertion sort, but unlike merge sort, heapsort sorts in place: only a constant number of array elements are stored outside the input array at any time. Thus, heapsort combines the better attributes of the two sorting algorithms we have already discussed.
Heapsort also introduces another algorithm design technique: the use of a data structure, in this case one we call a "heap," to manage information during the execution of the algorithm. Not only is the heap data structure useful for heapsort, but it also makes an efficient priority queue. The heap data structure will reappear in algorithms in later chapters.
We note that the term "heap" was originally coined in the context of heapsort, but it has since come to refer to "garbage-collected storage," such as the programming languages Lisp and Java provide. Our heap data structure is not garbage-collected storage, and whenever we refer to heaps in this book, we shall mean the structure defined in this chapter.
我的代码:
const n=10;
type arr=array[1..n] of integer;
var i,t:integer;
a:arr;
procedure heap(var a:arr;l,r:integer);
var i,j,k,t:integer;
begin
i:=2*l;j:=i+1;
if (i<=r ) and (a[i]>a[l]) then k:=i
else k:=l;
if (j<=r ) and (a[j]>a[k]) then k:=j;
if k<>l then begin
t:=a[l];a[l]:=a[k];a[k]:=t;
heap(a,k,r);
end;
end;
begin
for i:=1 to n do read(a[i]);
for i:=n div 2 downto 1 do heap(a,i,n);
for i:=1 to n-1 do
begin
write(a[1],' ');
t:=a[1];
a[1]:=a[n-i+1];
a[n-i+1]:=t;
heap(a,1,n-i);
end;
writeln(a[1]);
end.
or
program duipx;
const n=8;
type arr=array[1..n] of integer;
var a:arr;i:integer;
procedure sift(var a:arr;l,m:integer);
var i,j, t:integer;
begin
i:=l;j:=2*i;t:=a[i];
while j<=m do
begin
if (j<m) and (a[j]>a[j+1]) then j:=j+1;
if t>a[j] then
begin a[i]:=a[j];i:=j;j:=2*i; end
else exit;
a[i]:=t;
end;
end;
begin
for i:=1 to n do read(a[i]);
for i:=(n div 2) downto 1 do
sift(a,i,n);
for i:=n downto 2 do
begin
write(a[1]:4);
a[1]:=a[i];
sift(a,1,i-1);
end;
writeln(a[1]:4);
end.