Jumat, 24 Juni 2011

Program C++ Linier Search

At this time we will learn about the linear search. Suppose there is an array with a lot of data as much as size. The principle of the linear search, any data on the array will be compared with the keywords until the final data. Please look friends algorithm and the code ...!

Algoritma :
Function pencarianLinier(input array : larik; kuci, ukuran : integer)
Deklarasi
ketemu  : boolean
i,n          : integer
Deskripsi
ketemu <= false {belum ketemu }
n <= 1   { mulai dari elemen pertama }
while ((n < ukuran) and (not ketemu)) do
if (array[n] = kunci) then            { dibandingkan }
ketemu <= true                  { data ketemu }
i <= n                                 { pada posisi ke-i, posisi disimpan }
endif
else n <= n + 1                            { cek data berikutnya }
endwhile
if ketemu then pecarianLinier <= i         { dat ketemu pada posisi ke-I }
else pencarianLinier <= -1                { data tidak ketemu }
endif

Berikut kode programnya :
#include <iostream.h>
#definie UKURAN 100

int pencarian_linier(int array[], int kunci, int ukuran)
{ int i;
  for (i=0; i<=ukuran-1; i++)
if (array[i]==kunci)
return i;
return -1;
}

void main(){
int a[UKURAN], x, kunciPencarian, UKURAN);
for (x=0; x<=UKURAN-1; x++) a[x]=2*x;
cout<<"Bilangan yang ingin dicari : ";
cin>>kunciPencarian;
elemen = pencarianLinier(a,kunciPencarian,UKURAN)l;
if (elemen != -1)
cout<<kunciPencarian<<"ditemukan pada posisi elemen ke "<<elemen;
else
cout<<kunciPencarian<<"tidak ada.";

} 

explanation:
The program above is used for linear searches which look for a data element array using the search key. When the position of the ith data together with the key, it means that the data found in the ith position. When the end of the data, the data also found no means the key does not exist on the array. In this program uses a for loop and use the if ... else condition.

0 komentar:

Posting Komentar

Template by:

Free Blog Templates