#include<iostream>
#include<cstdlib>
using namespace std;
class search
{
int arr[10];
public:
bool linearsearch(int);
bool binarysearch(int);
void sort();
void readarray();
};
bool search::linearsearch(int ele)
{
for(int i=0;i<10;i++)
if(arr[i]==ele)
return true;
return false;
}
bool search::binarysearch(int ele)
{
int low=0,high=9,mid;
search ob;
ob.sort();
while(low<=high)
{
mid=(low+high)/2;
if(ele==arr[mid])
return true;
else if(ele<arr[mid])
high=mid-1;
else
low=mid+1;
}
return false;
}
void search::sort()
{
for(int i=0;i<9;i++)
for(int j=0;j<9;j++)
if(arr[j]>arr[j+1])
{
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
void search::readarray()
{
cout<<"Enter the elements of the array:";
for(int i=0;i<10;i++)
cin>>arr[i];
}
int main()
{
search ob;
int ele,choice;
bool b;
ob.readarray();
cout<<"Enter the element to be found:";
cin>>ele;
cout<<"Which search would you like to use?\n\n1.Linear Search\n2.Binary search\n";
cin>>choice;
switch(choice)
{
case 1:
{
b=ob.linearsearch(ele);
if(b==true)
cout<<"Element found.";
else
cout<<"Element not found.";
}
break;
case 2:
{
b=ob.binarysearch(ele);
if(b==true)
cout<<"Element found.";
else
cout<<"Element not found.";
}
break;
}
}
OUTPUT:-
Enter the elements of the array:2
1
4
6
2
3
1
4
5
6
Enter the element to be found:5
Which search would you like to use?
1.Linear Search
2.Binary search
1
Element found.
No comments:
Post a Comment