Linear Search
linearSearch function has 3 input parameters:
first is the starting address of the array
second is the size of the array
third is the value to be searched
This function returns the index of the value found in the array and returns 1 in case if the value is not found.
Code
#include "stdafx.h"
#include "iostream"
#include "conio.h"
using namespace std;
int linearSearch(int*arr,int size,int valToSearch)
{
for(int i=0;i<size;i++)
{
if(arr[i]==valToSearch)
return i;
}
return -1;
}
int main()
{
int*arr;
int size=0;
int valToSearch;
cout<<"Enter the size of integer array > ";
cin>>size;
cout<<"Enter the value to search > ";
cin>>valToSearch;
arr=new int[size];
for(int i=0;i<size;i++)
{
cout<<"arr["<<i<<"] = ";
cin>>arr[i];
}
int result=0;
result=linearSearch(arr,size,valToSearch);
if(result!=-1)
cout<<valToSearch<<" found at index number "<<result<<endl;
else
cerr<<valToSearch<<" not found"<<endl;
delete arr;
_getche();
return 0;
}
0 comments:
Post a Comment