Jumaat, Januari 10, 2014

C++ : Linear search a.k.a Sequential search (Brute force)

#include <iostream>

using namespace std;

// Size of array nums
const int Element=10;
//Function prototype
int linearSearch(int[], int, int);

int main()
{
 // Listing of element in array nums
 int nums[Element]={5,10,22,32,45,67,73,98,99,101};
 int item,location;

 cout<<"Enter the item you are searching for: ";
 cin>>item;

 // Calling  and passing parameter to function linearSearch()
 location=linearSearch(nums,Element,item);

 // Passing function result back to main()
    if(location> -1)
        cout<<"The item was found at index location "<<location<<endl;
    else
        cout<<"The item was not found in the array\n";
 return 0;
}

// compare key to every element of array until location is
// found or until end of array is reached. Return subscript of
// element if key is found or -1 if key not found
int linearSearch(int list[ ],int size,int key) {
 int i;
  for(i=0;i<size;i++) {
   if (list[i]==key)
   return  i;
  } return -1;
}

0 ulasan:

Catat Ulasan

Pesanan daripada penulis :
Selamat datang ke 0x2013LΣΣT. Sekiranya anda mempunyai persoalan, pandangan, permintaan, bantuan, cadangan dan sebagainya. Tinggalkan pesanan anda ke dalam kotak komen. Terima kasih !
- http://0x2013.blogspot.com -