Embed presentation
Download to read offline
![Write and implement a recursive version of the binary search algorithm. Also, write a program to
test your algorithm
Solution
#include <iostream.h>
using namespace std;
int binarySearch(int a[],int low,int high,int val);
int main()
{
inti,j,id[10]={5,10,15,20,30,40,50,60,70,80},key=30,max=10,temp;
temp= binarySearch(id,0,max,key);
cout<<temp<<endl;
system("pause");
return 0;
}
int binarySearch(int a[],int low,int high,int val)
{Â Â int mid;
if(low>high)
return -1;
else
{mid=(low+high)/2;
if (a[mid]==val)
return mid;
else if(a[mid]<val)
returnbinarySearch(a,mid+1,high,val);
else
returnbinarySearch(a,low,mid-1,val);
}
}](https://image.slidesharecdn.com/writeandimplementarecursiveversionofthebinarysearchalgorithm-230129053143-1bb34f32/85/Write-and-implement-a-recursive-version-of-the-binary-search-algorithm-docx-1-320.jpg)

The document provides a recursive implementation of the binary search algorithm in C++. It includes code for both the binary search function and a main program to test the function using a predefined array. The implementation returns the index of the searched value if found or -1 if not found.
![Write and implement a recursive version of the binary search algorithm. Also, write a program to
test your algorithm
Solution
#include <iostream.h>
using namespace std;
int binarySearch(int a[],int low,int high,int val);
int main()
{
inti,j,id[10]={5,10,15,20,30,40,50,60,70,80},key=30,max=10,temp;
temp= binarySearch(id,0,max,key);
cout<<temp<<endl;
system("pause");
return 0;
}
int binarySearch(int a[],int low,int high,int val)
{Â Â int mid;
if(low>high)
return -1;
else
{mid=(low+high)/2;
if (a[mid]==val)
return mid;
else if(a[mid]<val)
returnbinarySearch(a,mid+1,high,val);
else
returnbinarySearch(a,low,mid-1,val);
}
}](https://image.slidesharecdn.com/writeandimplementarecursiveversionofthebinarysearchalgorithm-230129053143-1bb34f32/85/Write-and-implement-a-recursive-version-of-the-binary-search-algorithm-docx-1-320.jpg)
