Sorting algorithms/Heapsort: Difference between revisions
→{{header|Pascal}}: replaced incorrect previous version
(→{{header|Pascal}}: replaced incorrect previous version) |
|||
Line 4,291:
=={{header|Pascal}}==
{{works with|FPC}}
An example, which works on arrays with arbitrary bounds :-)
<syntaxhighlight lang="pascal">
program HeapSortDemo;
{$mode objfpc}{$h+}{$b-}
var▼
var▼
begin▼
root := start;▼
while root * 2 - start + 1 <= ende do▼
begin▼
if (child + 1 <= ende) and (a[child] < a[child + 1]) then▼
if a[root] < a[child] then▼
a[root] := a[child];▼
a[child] := swap;▼
end▼
end;▼
end;▼
procedure
procedure SiftDown(Root, Last: Integer);
var
begin
▲ end else exit;
end;
end;
▲var
I, Tmp: Integer;
var▼
SiftDown(I, High(a));
for I := High(a) downto 1 do begin
SiftDown(0, I
end;
procedure PrintArray(const Name: string; const A: array of Integer);
I: Integer;
begin
Write(Name, ': [');
for I := 0 to High(A) - 1 do
WriteLn(A[High(A)], ']');
end;▼
a1: array[-7..5] of Integer = (-34, -20, 30, 13, 36, -10, 5, -25, 9, 19, 35, -50, 29);
a2: array of Integer = (-9, 42, -38, -5, -38, 0, 0, -15, 37, 7, -7, 40);
HeapSort(a1);
▲ for i := low(data) to high(data) do
PrintArray('a1', a1);
PrintArray('a2', a2);
{{out}}
<pre>
a1: [-50, -34, -25, -20, -10, 5, 9, 13, 19, 29, 30, 35, 36]
a2: [-38, -38, -15, -9, -7, -5, 0, 0, 7, 37, 40, 42]
</pre>
|