BINARY SEARCH
BINARY SEARCH
It is a Different type of Search in which we divide the array into Two Parts from the middle element. (The array Must be sorted before we do this)
- Step 1: First divide the array of elements in half.
- Step 2: In the second step we compare the target value with the middle element of the array. If it matches the middle element then search ends here and doesnβt proceed further.
- Step 3: Else if the element less than the middle element then we begin the search in lower half of the array.
- Step 4: Else if the element is greater than the middle element then we begin the search in greater half of the array.
- Step 5: We will repeat the steps 3 ,4 and 5 until our target element is found.
So That's Simple Now
#include<iostream>
using namespace std;
int main()
{
int search(int [],int,int);
int n,i,a[100],e,res;
cout<<"How Many Elements:";
cin>>n;
cout<<"\nEnter Elements of Array in Ascending order\n";
for(i=0;i<n;++i)
{
cin>>a[i];
}
cout<<"\nEnter element to search:";
cin>>e;
res=search(a,n,e);
if(res!=-1)
cout<<"\nElement found at position "<<res+1;
else
cout<<"\nElement is not found....!!!";
return 0;
}
int search(int a[],int n,int e)
{
int f,l,m;
f=0;
l=n-1;
while(f<=l)
{
m=(f+l)/2;
if(e==a[m])
return(m);
else
if(e>a[m])
f=m+1;
else
l=m-1;
}
return -1;
}
21
