In: Computer Science
implement this search function using CPP Coding
language
bool binarySearch(vector<int>vec,int low,int high, int
search)
Test your code in
main
#include <bits/stdc++.h>
using namespace std;
//implementing required funtion
bool binarySearch(vector<int> vec,int low,int high,int
search)
{
if(low<=high)
{
int mid=(low+high)/2;
if(vec[mid]==search)
return true;
else if(vec[mid]<search)
return binarySearch(vec,mid+1,high,search);
else
return binarySearch(vec,low,mid-1,search);
}
return false;
}
int main()
{
vector<int> vec;
//inserting elements in vector in ascending order
//as binary search works only on sorted elements
vec.push_back(11);
vec.push_back(24);
vec.push_back(29);
vec.push_back(35);
vec.push_back(36);
vec.push_back(40);
vec.push_back(43);
vec.push_back(47);
vec.push_back(55);
vec.push_back(67);
int n=vec.size();
//passing index of first element(0) and last element(n-1)
if(binarySearch(vec,0,n-1,22))
{
cout<<"22 is present"<<endl;
}
else
{
cout<<"22 is not present"<<endl;
}
if(binarySearch(vec,0,n-1,43))
{
cout<<"43 is present"<<endl;
}
else
{
cout<<"43 is not present"<<endl;
}
return 0;
}