Minggu, 08 Juni 2014

Program Binary Search

 Langsung saja nih tanpa basa-basi, Berikut Coding nya :


uses crt;
const
i = 1;
n = 8;

var
l : array [i..n] of byte;

x,y,z,tmp,idx, min : byte;
posisi,t,c,b,a,cari : integer;
ketemu : boolean;


begin
clrscr;
l [1] := 1;
l [2] := 3;
l [3] := 1;
l [4] := 4;
l [5] := 5;
l [6] := 2;
l[7] := 6;
l[8] := 1;
writeln;
for x := i to n do
write (l[x], ' ');
writeln;


for y := 2 to n do
    begin
    idx := y-1;
    writeln;
    write ('langkah ',y-1,' : ');
    for x := y to n do
        if l[idx] > l[x] then
        idx := x;

            tmp := l[y-1];
            l[y-1] := l[idx];
            l[idx] := tmp;
for x := i to n do
begin
write (l[x],' ');
end;
end;
readln;

clrscr;
write ('data setelah di urutkan : ');
for x := i to n do
begin
write (l[x],' ');
end;
b := i;
a := n;
writeln;
write ('data yang ingin di cari : '); read (cari);
ketemu := false;
c := 0;
while (not ketemu) and ( a >= b) do
begin
c := c + 1;
t := (b + a) div 2;
     if cari = l[t] then
     begin
     posisi := t;
     ketemu := true;
     end;
         if cari > l[t]
         then b := t + 1
         else
         a := t - 1;

end;
writeln ('data adalah ',l[posisi]);
writeln ('posisinya berada di indeks ',posisi);
writeln ('jumlah perbandingan nya : ',c);
readln;

readln;
end.


SEMOGA MEMBANTU.!!

Tidak ada komentar:

Posting Komentar