Here is a C++ program to implement binary search using recursion
SOURCE CODE OUTPUT
#include<iostream>
#include<math.h>
using namespace std;
int binary(int (&a)[20],int low,int high,int key)
{
int mid=(low+high)/2;
if(low>high)
return -1;
else if(a[mid]==key)
return mid;
else if(key>a[mid])
binary(a,mid+1,high,key);
else
binary(a,low,mid-1,key);
}
int main()
{
int result,n,a[20],key;
cout<<"How many numbers to be entered ";
cin>>n;
cout<<"Enter number : ";
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"Enter element to be searched : ";
cin>>key;
result=binary(a,0,n-1,key);
if(result==-1)
cout<<"Element is not found";
else
cout<<"Element is found at "<<result+1<<" position ";
return 0;
}
#include<math.h>
using namespace std;
int binary(int (&a)[20],int low,int high,int key)
{
int mid=(low+high)/2;
if(low>high)
return -1;
else if(a[mid]==key)
return mid;
else if(key>a[mid])
binary(a,mid+1,high,key);
else
binary(a,low,mid-1,key);
}
int main()
{
int result,n,a[20],key;
cout<<"How many numbers to be entered ";
cin>>n;
cout<<"Enter number : ";
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"Enter element to be searched : ";
cin>>key;
result=binary(a,0,n-1,key);
if(result==-1)
cout<<"Element is not found";
else
cout<<"Element is found at "<<result+1<<" position ";
return 0;
}
Any questions regarding to program please write in comments.
No comments:
Post a Comment