Jumat, 24 Juni 2011

Program C++ Binary Search


Hmmmm…. Setelah mempelajari tentang Linier Search sekarang saya akan membahas tentang Binary Search. Okee…. Langsung saja teman-teman bisa lihat algoritma dan codingnya. Semoga bermanfaat ,,, :) thankz before….

Algoritma :
Fuction pencarianBiner(input array : larik ; kunci, low, high : integer) : inteeger
Deklarasi
ketemu      : boolean
i, middle    : integer

Deskripsi
ketemu <= false
while (low<=high) and (not ketemu) do
middle <= (low+high) div 2
if (kunci = aray[middle]) then ketemuß true{ data pencarian = data di tengah }
else if (kunci < aray[middle]) then
high <= middle – 1 { data akan dicari lagi di sebelah kiri}
else low <= middle + 1                         {data akan dicari lagi di sebelah kanan }
endif
endwhile
if ketemu then pencarianBiner := middle
else pencarianBiner := -1
endif

Berikut kode programnya :
#include <iostream.h>
#define UKURAN 15
void cetakHeader(void)
{ int i;
cout<<"\nSubscript :\n";
for (i=0; i<=ukuran-1; i++)
cout<<i<<"";
for (i=1; i<=4*UKURAN; i++)
cout<<"-";
cout<<"\n";
}
void cetakBaris(int b[], int low, int mid, int high){
int i;
for (i=0; i<=UKURAN-1; i++)0
if (i<low || i>high){
  cout<<" ";
} else if (i==mid){
  cout<<"*"<<b[i];}
else {
  cout<<b[i]<< " ";
  cout<<"\n";
}
}

int pencarianBiner(int b[], int kunciPencarian, int low, int high){
int i,middle;
while (low <= high){
middle = (low + high)/2;
cetakBaris(b, low, middle, high);
if (kunciPencarian == b[middle])
return middle;
else if (kunciPencarian < b[middle])
high = middle-1;
else low = middle+1;
}
return-1;
}

main(){
int a[UKURAN],i,kunci, hasil;
for (i=0; i<=UKURAN-1; i++)
a[i]=2*I;
cout<<"Masukan bilangan antara 0-28 :";
cin>>kunci;
cetakHeader();
hasil = pencarianBiner(a,kunci,0,UKURAN-1);
if (hasil != -1){
cout<<kunci<<"ditemukan pada posisi :"<<hasil;}
else {
    cout<<kunci<<"tidak ditemukan";
return 0;
}


explanation:
The above program on a binary search where each keyword search will always be compared with data residing in the middle (the middle) when the same means that the data met, if not, will "be seen" whether there is data next to the "left" (meaning that smaller data of data in the middle) or next to the "right" (meaning the data is larger than the data in the middle). When the data is to the left, do a search in the same way (while data is located on the right will be ignored). So, every time a search, the data is always "split" into two parts (binary), until the "point" (when equal to the midpoint, the search is not done anymore, if not, to the last comparison data are also not the same, meaning the data not found in the array Aray).


0 komentar:

Posting Komentar

Template by:

Free Blog Templates