09/02/19

Contoh Program Bubble sort naik, turun dan insertion sort pada pascal


Koding untuk bubble sort Naik
program arh_bsort_menaik;

uses wincrt;

var i,n,j : integer;
a: array [1..100] of integer;

procedure buble;
var z: integer;
begin
for i:= 1 to n-1 do
begin
for j:= n downto i+1 do
begin
if a[j] < a[j-1] then
begin
z:= a[j];
a[j]:= a[j-1];
a[j-1]:=z;
end;
end;
end;

end;
begin
write('masukkan banyak larik (maks 100) : '); readln(n);
for i:= 1 to n do
begin write('A[',i,'] : '); readln(a[i]);
end;

buble;
write('data setelah diurutkan : ');

for j:=1 to n do
write (a[j],' ');
end.




Koding untuk bubble sort menurun
program arh_bsort_menurun;

uses wincrt;

var i,n,j : integer;
a: array [1..100] of integer;

procedure buble;
var z: integer;
begin
for i:= 1 to n-1 do
begin
for j:= n downto i+1 do
begin
if a[j] > a[j-1] then
begin
z:= a[j];
a[j]:= a[j-1];
a[j-1]:=z;
end;
end;
end;

end;
begin
write('masukkan banyak larik (maks 100) : '); readln(n);
for i:= 1 to n do
begin write('A[',i,'] : '); readln(a[i]);
end;

buble;
write('data setelah diurutkan : ');

for j:=1 to n do
write (a[j],' ');
end.



Insertion Sort
program insertion(input,output);
const
MAX = 10;
var
a : array[1..MAX] of integer;
i, n : integer;

procedure insertion_sort;
var
i, pos : integer;
value : integer;
done : boolean;
begin
for i := 2 to n do
begin

value := a[i];
pos := i;
done := false;
while not done do
begin
if pos <= 1 then
done := true
else if value >= a[pos-1] then
done := true
else
begin
a[pos] := a[pos-1];
pos := pos-1
end
end; {while}

a[pos] := value;

end {for}
end;

begin { main }
writeln('How many number would you like to sort (max=',MAX:2,') ?');
readln(n);

writeln('Enter in ',n:1,' numbers:');
for i := 1 to n do
read(a[i]);

insertion_sort;

for i := 1 to n do
write(a[i]:1,' ');
writeln
end.



1 komentar: