#include<iostream.h>
#include<process.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
int linser(int[],int,int);
void main()
{ clrscr();
int a[50],item,n,index,ch;
cout<<"\n\n\n\t\t\t\t\t\tOPTIONS\n\t\t\t\t\t\t...........";
cout<<"\n\n1.Linear Search\n2.Binary Search\n3.Exit.";
cout<<"\n\n\nEnter your choice :";
cin>>ch;
switch(ch)
{case 1:
{ clrscr();
cout<<"ENTER THE DESIRED ARRAY SIZE(max. 50):";
cin>>n;
cout<<"\nENTER ARRAY ELEMENTS\n";
for(int i=0;i<n;i++)
{ cin>>a[i];
}
cout<<"\nENTER ELEMENT TO BE SEARCHED FOR...";
cin>>item;
index=linser(a,n,item);
if(index==-1)
cout<<"\nSorry!!Given element could not be found.\n";
else
cout<<"\nElement found at index:"<<index<<",Position:"<<index+1<<"\n";
break;
}
case 2:
{ clrscr();
cout<<"ENTER THE DESIRED ARRAY SIZE(max. 50):";
cin>>n;
cout<<"\nENTER ARRAY ELEMENTS\n";
for(int i=0;i<n;i++)
{ cin>>a[i];
}
cout<<"\nENTER ELEMENT TO BE SEARCHED FOR...";
cin>>item;
index=binser(a,n,item);
if(index==-1)
cout<<"\nSorry!!Given element could not be found.\n";
else
cout<<"\nElement found at index:"<<index<<",Position:"<<index+1<<"\n";
break;
getch();
}
int linser(int a[],int size,int item)
{ for(int i=0;i<size;i++)
{ if(a[i]==item)
return i;
}
return -1;
}
int binser(int a[],int size,int item)
{ int beg,last,mid;
beg=0;
last=size-1;
while(beg<=last)
{ mid=(beg+last)/2;
if(item==a[mid])
return mid;
else if(item>a[mid])
beg=mid+1;
else
last=mid-1;
}
return -1;
}
#include<process.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
int linser(int[],int,int);
void main()
{ clrscr();
int a[50],item,n,index,ch;
cout<<"\n\n\n\t\t\t\t\t\tOPTIONS\n\t\t\t\t\t\t...........";
cout<<"\n\n1.Linear Search\n2.Binary Search\n3.Exit.";
cout<<"\n\n\nEnter your choice :";
cin>>ch;
switch(ch)
{case 1:
{ clrscr();
cout<<"ENTER THE DESIRED ARRAY SIZE(max. 50):";
cin>>n;
cout<<"\nENTER ARRAY ELEMENTS\n";
for(int i=0;i<n;i++)
{ cin>>a[i];
}
cout<<"\nENTER ELEMENT TO BE SEARCHED FOR...";
cin>>item;
index=linser(a,n,item);
if(index==-1)
cout<<"\nSorry!!Given element could not be found.\n";
else
cout<<"\nElement found at index:"<<index<<",Position:"<<index+1<<"\n";
break;
}
case 2:
{ clrscr();
cout<<"ENTER THE DESIRED ARRAY SIZE(max. 50):";
cin>>n;
cout<<"\nENTER ARRAY ELEMENTS\n";
for(int i=0;i<n;i++)
{ cin>>a[i];
}
cout<<"\nENTER ELEMENT TO BE SEARCHED FOR...";
cin>>item;
index=binser(a,n,item);
if(index==-1)
cout<<"\nSorry!!Given element could not be found.\n";
else
cout<<"\nElement found at index:"<<index<<",Position:"<<index+1<<"\n";
break;
getch();
}
int linser(int a[],int size,int item)
{ for(int i=0;i<size;i++)
{ if(a[i]==item)
return i;
}
return -1;
}
int binser(int a[],int size,int item)
{ int beg,last,mid;
beg=0;
last=size-1;
while(beg<=last)
{ mid=(beg+last)/2;
if(item==a[mid])
return mid;
else if(item>a[mid])
beg=mid+1;
else
last=mid-1;
}
return -1;
}
No comments:
Post a Comment