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);
}
}
Write and implement a recursive version of the binary search algorithm.docx

Write and implement a recursive version of the binary search algorithm.docx

  • 1.
    Write and implementa 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); } }