Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

//Linear search

#include<iostream>
using namespace std;

int main()
{
int n,i,e;
//int flag=0;
cout<<"enter the size of an Array"<<endl;
cin>>n;
int a[n];
cout<<"\n Enter the "<<n<<" elements into an array"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"\nEntered array is \n"<<endl;
for(i=0;i<n;i++)
{
cout<<a[i]<<'\t';
}
cout<<"\n \n Enter the element you want to search \n"<<endl;
cin>>e;

for(i=0;i<n;i++)
{
if (a[i]== e)
{
cout<<"Element is found at index "<<i;
//flag=1;
break;
}
}
if (i==n)
{
cout<<"Element if not present";
}
//if (flag==0)
//{
//cout<<"Element if not present";
//}
}
// Binary search
#include<iostream>
using namespace std;

int main()
{
int n=8,i,e,l=0,r=n-1,mid;
int a[n]={10,15,30,42,55,65,72,90};

cout<<"\nEntered array is \n"<<endl;


for(i=0;i<8;i++)
{
cout<<a[i]<<'\t';
}
cout<<"\n \n Enter the element you want to search \n"<<endl;
cin>>e;

mid = (l+r)/2;
while (l <= r)
{
if(a[mid] < e)
{
l = mid + 1;

}
else if(a[mid] == e)
{
cout<<e<<" found in the array at the location "<<mid+1<<"\n";
break;
}

else {
r = mid - 1;
}
mid = (l + r)/2;
}
if(l > r)
{
cout<<e<<" is not found in the array";
}
}

You might also like