binary search using template


#include<iostream.h>
#include<conio.h>
enum boolean {false,true};
template<class t>
int binsearch(t data[],t ele,int low,int high)
{
if(low>high)
return -1;
int mid=(low+high)/2;
if(ele<data[mid])
return binsearch(data,ele,low,mid-1);
else
if(ele>data[mid])
return binsearch(data,ele,mid+1,high);
return mid;
}
void main()
{
int elem,size,num[25],index;
clrscr();


cout<<"how many elements?"<<endl;
cin>>size;
cout<<"Enter element in ascending order....\n";
for(int i=0;i<size;i++)
cin>>num[i];
cout<<"Enter element:"<<endl;
cin>>elem;
if((index=binsearch(num,elem,0,size))==-1)
cout<<"Element "<<elem<<" not found"<<endl;
else
cout<<"Element '"<<elem<<"' found at position "<<index<<endl;


getch();
}
Previous
Next Post »