You are on page 1of 3

//LINEAR AND BINARY SEARCH

#include<iostream.h>
#include<conio.h>
#include<process.h>

int Lsearch(int AR[],int size,int element)


{
for(int i=0;i<size;i++)
{
if (AR[i]==element) return i;
}
return -1;
getch();
}

int Bsearch(int AR[],int size,int element)


{
int beg,last,mid;
beg=0; last=size-1;
while(beg<=last)
{
mid=(beg+last)/2;
if(element==AR[mid])
return mid;
else if(element>AR[mid])
beg=mid+1;
else
last=mid-1;
}
return -1; }
void main( )
{
int AR[50],element,N,index,ch;
char opt='y';
cout<<"\nEnter desired array size(max.50)::";
cin>>N;
cout<<"\nEnter array element(must be sorted in asce order)";
for(int i=0;i<N;i++)
cin>>AR[i];
do
{
cout<<"\nEnter element to be searched for::";
cin>>element;
cout<<"\n MENU";
cout<<"\n 1. LINEAR SEARCH";
cout<<"\n 2. BINARY SEARCH";
cout<<"\n 3. EXIT";
cout<<"\n Enter ur choice::";
cin>>ch;
switch(ch)
{
case 1: index=Lsearch(AR,N,element);
break;
case 2:index=Bsearch(AR,N,element);
break;
case 3:exit(0);
}
if(index==-1)
cout<<"\nsorry!! given element could not be found,\n";
else
cout<<"\nElement found at index : " << index<< "position:"
<<index+1<<endl;

cout<<"\n Do u want to continue(Y/N)::";


cin>>opt;
}while(opt=='y' || opt=='Y');
}

You might also like