C++ program to demonstrate binary search

This program implements binary search in C++.  Binary search requires that the array be sorted in either ascending or descending order. The algorithm then compares the middle element in the array with the item to be searched, if a match is found its position is returned. Otherwise if the item to be searched is less than the middle element, the algorithm proceeds with the elements which are on the left side of the middle element, or if the item to be searched is greater than the middle element, the algorithm proceeds with the elements which comes after the middle element.  



Program



#include<iostream.h>
#include<conio.h>
void main()
{
          clrscr();
          int a[50],*p,n,ele,i,beg=0,end,mid;
          cout<<"Enter the no.of elements:";
          cin>>n;
          cout<<"\nEnter the elements in ascending order:";
          for(i=0;i<n;i++)
          {
                   cin>>a[i];
          }
          cout<<"\nEnter the element to be searched:";
          cin>>ele;
          beg=0,end=n-1;
          while(beg<=end)
          {
                   mid=(beg+end)/2;
                   p=&a[mid];
                   if(*p==ele)break;
                   else if(ele>*p) beg=mid+1;
                   else end=mid-1;
          }
          if(beg<=end)
          cout<<"\nThe element "<<ele<<" found at position "<<mid+1;
          else
          cout<<"\nnot found";
          getch();
}



Binary search program in C++
Binary Search in C++

No comments: