C++ program to search an element in sorted array using Binary search

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int x,y[100],z,i,j,v,beg,end,mid,n;
cout<<"Enter size of array:- ";
cin>>x;
cout<<"Enter Elements in array:- ";
for(i=0;i<x;i++)
{
 cin>>y[i];
}

for(i=0;i<x;i++)
  {
   for(j=i+1;j<x;j++)
    {
     if(y[i]>y[j])
      {
       v=y[j];
       y[j]=y[i];
       y[i]=v;
      }
    }
  }
cout<<"Sorted array is:- "<<endl;
for(i=0;i<x;i++)
 {
  cout<<y[i]<<endl;
 }

cout<<"Enter element you want to search:- ";
cin>>n;
beg=1;
end=x;
mid=(beg+end)/2;

while(beg<=end && y[mid]!=n)
 {
  if(y[mid]<n)
   {
    beg=mid+1;
   }
   else
   {
    end=mid-1;
   }
   mid=(beg+end)/2;
 }
 if(y[mid]==n)
  {
   mid++;
   cout<<"Element is found at location:- "<<mid;
  }
  else
  {
   cout<<"Element is not found";
  }
 getch();
 }

binary search

Leave a Reply

Your email address will not be published. Required fields are marked *