Tuesday, January 19, 2010

LINEAR SEARCH AND BINARY SEARCH

#include
#include
void main()
{
int a[100],n,i,item,l=-1,j,c=0,beg,end,mid,flag=0;
clrscr();
cout<<"\nEnter the number of element:";
cin>>n;
cout<<"Enter the number:\n";
for(i=0;i<=n-1;i++)
{
cin>>a[i];
}
do
{
cout<<"\n1:Linear search\n2:Binary search\n3:exit\n";
cin>>j;
switch(j)
{
case 1:
{
cout<<"Enter the no. to be search\n";
cin>>item;
for(i=0;i<=n-1;i++)
{
if(item==a[i])
{
l=i+1;
break;
}
}
if(l>=0)
cout<<"\n"< else
cout<<"\nItem does not exits";
break;
}
case 2:
{
cout<<"Enter the element to be searched";
cin>>item;
beg=0;
end=n-1;
while((beg<=end)&&(item!=a[mid]))
{
mid=((beg+end)/2);
if(item==a[mid])
{
cout<<"search is successfull\n";
cout<<"position of the item"< flag=flag+1;
}
if(item end=mid-1;
else
beg=mid+1;
}
if(flag==0)
cout<<"search is not successfull\n";
break;
}
case 3:
{
c++;
}
}
}while(c==0);
}

No comments: