C++ Program to explain Binary search in Array


#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<<"
Enter Elements of Array in Ascending order";
 for(i=0;i<n;++i)
  {
   cin>>a[i];
  }

 cout<<"
 Enter element to search:";
 cin>>e;
 res=search(a,n,e);
  if(res!=-1)
  cout<<
 Element found at position "<<res+1;
  else
   cout<<"
 Element 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;
}

Output

How Many Elements:5
Enter Elements of Array in Ascending order
25 20 40 45 10
Enter element to search:45
Element found at position 4

Explanation

Binary search is an algorithm used to search for an element in a sorted array. In this algorithm the targeted element is compared with middle element.