Selasa, 20 Januari 2009

Source code binary search (dalam pascal)

Berikut saya sajikan tentang penerapan algoritma binary Search. Di mana binary search bekerja saat data sudah diurutkan terlebih dahulu.

===================================================================================

uses crt;

var
a : array[1..10] of byte;
low, high, mid, n, i, x : byte;
found : boolean;

begin
// n menunjukkan banyaknya data yang hendak dimasukkan ke dalam array
n := 10;
low:=1;
high:=n;
found := false;

clrscr;

for i:=1 to 10 do
begin
write('Angka ke- ',i);
write(' : ');
readln(a[i]);
end;

write('Masukkan target yang dicari : ');
readln(x);

while ((low <= high) and (found = false)) do
begin
mid := low + ((high-low) div 2);
if (a[mid] = x) then found:=true
else
if (a[mid] < x) then
low := mid + 1
else
if(a[mid] > x) then
high := mid;
end;

writeln('Data diketemukan di index ke : ',mid);
readln;
end.

1 komentar:

as mengatakan...

bro cara kerja nya gimana ya? mekanisme program nya