using namespace std;
class search_item
{
int a[20];
int size;
public:
search_item()
{
size=0;
}
void get_array()
{
cout<<"enter the size\n";
cin>>size;
cout<<"Enter the items\n";
for(int i=0;i<size;i++)
{
cin>>a[i];
}
}
void put_array()
{
cout<<"ARRAY IS\n";
for(int i=0;i<size;i++)
{
cout<<a[i];
}
}
void sequential_search(int item)
{
int loc,flag;
for(int i=0;i<size;i++)
{
if(item==a[i])
{
loc=i;
flag=1;
break;
}
}
if(flag==1)
cout<<"Item found at "<<loc+1<<endl;
else
cout<<"Not found\n";
}
void binary_search(int item)
{
int mid,beg=0,end=size-1;
mid=(beg+end)/2;
while(beg<=end&&item!=a[mid])
{
if(item<a[mid])
{
end=mid-1;
}
else
{
beg=mid+1;
}
mid=(beg+end)/2;
}
if(item==a[mid])
cout<<"item found at"<<mid+1<<endl;
else
cout<<"NOT found\n";
}
};
int main()
{
int item,choice;
search_item o1;
while(choice!=3)
{
cout<<"\n1:squential search\n2:binary search\n";
cout<<"enter the choice";
cin>>choice;
switch(choice)
{
case 1: o1.get_array();
cout<<"Enter the item to be searched\n";
cin>>item;
o1.sequential_search(item);
break;
case 2:o1.get_array();
cout<<"Enter the item to be searched\n";
cin>>item;
o1.binary_search(item);
break;
}
}
return 0;
}
Comments