0% found this document useful (0 votes)
36 views

int Flag 0 : //linear Search

This document contains code for linear search and binary search algorithms. The linear search algorithm iterates through an array, compares each element to the target value, and returns the index if found. The binary search algorithm uses a divide and conquer approach, repeatedly dividing the search space in half and checking the middle element to see if it is the target. It returns the index if found or indicates the element is not present.

Uploaded by

Azeem Ansari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

int Flag 0 : //linear Search

This document contains code for linear search and binary search algorithms. The linear search algorithm iterates through an array, compares each element to the target value, and returns the index if found. The binary search algorithm uses a divide and conquer approach, repeatedly dividing the search space in half and checking the middle element to see if it is the target. It returns the index if found or indicates the element is not present.

Uploaded by

Azeem Ansari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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