binary search implementation using recursion
#include<iostream>
using namespace std;
bool binary(int a[],int n,int m,int low,int up)
{
int mid,key_flag=0;
if(low <= up){
mid=(low+up)/2;
if(m==a[mid]){
key_flag=1; //found
}
else if(m < a[mid]){
return binary(a,n,m,low,mid-1);
}
else
return binary(a,n,m,mid+1,up);
}
else
return key_flag;
}
int main()
{
int a[10],i,n,m,key,low,up;
cout<<"Enter the size of an array: ";
cin>>n;
cout<<"Enter the elements of the array: " ;
for(i=0;i <= n;i++)
{
cin>>a[i];
}
system("CLS");
for(i=1;i <= n;i++)
{
cout<<"elements which you entered are \t"<<a[i]<<"\n";
}
cout<<"Enter the number to be search: ";
cin>>m;
low=0,up=n-1;
key=binary(a,n,m,low,up);
if(key==0)
cout<<"\n Number not found ";
else
cout<<"\n Number found !";
system("pause");
return 0;
}
Comments
Post a Comment