C++ program to implement Binary Search

#include<iostream>
using namespace std;
int binarysearch(int *a,int key,int n);

int main( )
{

             int *arr,n,key;
             cout<<"Enter how many elements :";
             cin>>n;
             arr=new int[n];
             cout<<endl<<"Enter elements : ";
             for(int i=0;i<n;i++)
             cin>>arr[i];
             cout<<endl<<"Enter the element to search :";
             cin>>key;
             int result=binarysearch(arr,key,n);
             if(result>=0)
             cout<<endl<<"Element found at"<<
             result+1<<"position";
             else cout<<endl<<"Element not found";
             return 0;
}
int binarysearch(int *arr,int key,int n)
{
             int low=0,high=n-1;
             while(low<=high)
             {
                  int middle=(low+high)/2;
                          if(key==arr[middle])
                              return middle;
                          else if(key>arr[middle])
                              low=middle+1;
                          else if(key<arr[middle])
                              high=middle-1;
             }
             return -1;
}

Input

Enter how many elements: 12

Enter elements :

10  11  13  16  17  20  22  28  30  33  44  87

Enter the element to search: 22

Output

Element found at 7 position

Try it yourself

Leave a comment

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