c is the code used Implement a function that searches for a
Solution
1)
#include<iostream>
using namespace std;
int search(int a[],int size,int k)//method which searches for a value, in a given array if it is found, then return its index, else returns -1
{
int i;
for(i=0;i<size;i++)
{
if(a[i]==k)return i;//when found returning index
}
return -1;//when not found returning -1
}
int main()
{
//testing..
int a[10]={1,7,5,4,2,8,6,9,3,10};
cout<<\"Found at:\"<<search(a,10,8)<<endl;
return 0;
}
output:-
Found at :5
2)
#include<iostream>
using namespace std;
bool binarySearch(int a[],int size,int k)//this method search for a value k in given sorted list a, and returns true if value is present , otherwise returns false
{ int h,l,m;
l=0;h=size;
m=(l+h)/2;
while(l<=h)
{
if(a[m]==k)return true;//if k is in a returning true
if(a[m]<k)
l=m+1;
else
h=m-1;
m=(l+h)/2;
}
return false;//when not found returning false...
}
int main()
{
int a[5]={1,2,3,4,5};
cout<<\"Found \"<<binarySearch(a,5,2)<<endl;
cout<<\"Found \"<<binarySearch(a,5,1)<<endl;
cout<<\"Found \"<<binarySearch(a,5,3)<<endl;
cout<<\"Found \"<<binarySearch(a,5,4)<<endl;
cout<<\"Found \"<<binarySearch(a,5,5)<<endl;
cout<<\"Found \"<<binarySearch(a,5,6)<<endl;
cout<<\"Found \"<<binarySearch(a,5,0)<<endl;
return 0;
}
output:
Found 1
Found 1
Found 1
Found 1
Found 1
Found 0
Found 0
//true value is printed as 1, and false value is printed as 0

