Linear Search Program using 1-D Array

Linear search method is one of the most taught searching algorithm in any computer class. Here we are implementing binary search method on un-sorted one dimensional array.

Here in this program we are initializing one dimensional array of integer of size 10 and one data member from the keyboard.  These values are now passed to a function named as “linear_search” that return “1” on successful search of the element and  “0” on unsuccessful search.

// program to search an element from a list of elements using linear search method
// Developed by : rakesh kumar

#include<iostream>
using namespace std;
int linear_search(int x[],int n, int data)
{
int found =0;
for(int i=0;i<n;i++)
if(x[i]==data)
found =1;

return found;
}
int main(){
int x[10],i,data,result;
//input phase
for(i=0;i<10;i++)
{
cout<<“Enter x[“<<i+1<<“] Element : “;
cin>>x[i];
}
cout<<“\n Enter element that you want to search :”;
cin>>data;
//processing phase
result = linear_search(x,10,data);
//output phase
if(result ==0)
cout<<“Element does not exists”;
else
cout<<“Element exist in this array”;

return 0;
}

Linear search is also known as a sequential search method and this method is the best method to locate any element when your list is not in any sequence.

The binary search method is used when your list is in any sorted order.  If you need any such program in C++ then please send your request through comments.

Author: rakesh kumar

cbsetoday.com is my online home, here I share all the information related to education, programming - and everything else that attract me. You can get in touch with me in these social sharing websites
Download File :

Leave a Reply