Senin, 30 Maret 2015

Metode Pengurutan Heap Sort dalam Pascal

Tags

Contoh program pascal metode heap sort

Source Code :
Program Heap_Sort;
Uses crt;
Type SArray = array [0..100] of integer;
Var n,i: integer;
    A: SArray;


Procedure swap ( var a, b: integer );
Var temp: integer;
Begin
  temp := a;
  a := b;
  b := temp;
end;

Procedure siftDown ( var A: SArray; start, akhir: integer );
Var root, child: integer;
Begin
  Root:=start;
  While (root*2+1) <= akhir do
  Begin
    Child:=root*2+1;
    If (child < akhir) and (A[child] < A[child+1]) then
    Child:=child+1;
    If (A[root]<A[child]) then
    Begin
      Swap (A[root], A[child]);
      Root:=child;
    End else
    break;
  End;
End;

Procedure heapify ( var A: SArray; count: integer );
Var start: integer;
Begin
  Start:=(count-1) div 2;
  While start>=0  do
  Begin
    SiftDown (A, start, count-1);
    Start:=start-1;
  End;
End;

Procedure heapSort( var A: SArray; n: integer );
Var akhir: integer;
Begin
  Heapify (A,n);
  Akhir:=n-1;
  While akhir>0 do
  Begin
    Swap(A[akhir], A[0]);
    Akhir:=akhir-1;
    siftDown (A, 0, akhir);
  End;
End;

Begin
  Clrscr;
  Writeln('Program Heap Sort');
  Writeln('=================');
  Writeln;
  Write ( 'Inputkan Jumlah Data : ' ); readln (n);
  Writeln;
  Write('Inputkan Data : ');
  For i := 0 to n-1 do
  Begin
    Gotoxy(17+(i*3),6); readln(A[i]);
  End;
  Writeln;
  heapSort(A,n);
  Write('Hasil Sorting : ');
  For i := 0 to n-1 do
  Begin
    Write(A[i],'  ');
  End;
  Readkey;
End.


Output :

1. Input jumlah data.


2. Input data.


3. Hasil sorting.


EmoticonEmoticon