C++ Program Code to perform binary search on an array of elements, which is arranged in ascending order

Leave a Comment
/* The following C++ Program Code will perform the binary search on a list of elements or array of elements, which is arranged in ascending orderThe user is first asked about the total number of elements & then he is asked to enter those many elements in the list in ascending order. The user can also use any sorting algorithm in order to get rid of this constraint*/
/* See bubble sorting algorithm, insertion sorting algorithm, merge sort algorithm, quick sort algorithm, & selection sort algorithm */

#include<iostream>
#include<stdlib.h>
using namespace std;

template<class T>
T bin(T a[20],T n,T t)
{
                 int l,r,mid;
                 l=0;
                 r=n-1;
                 while(l<=r)
                 {
                                   mid=(l+r)/2;
                                   if(t==a[mid])
                                   return mid;
                                   else
                                   if(t<a[mid])
                                   r=mid-1;
                                   else
                                   l=mid+1;
                 }
                 return -1;
}

int main()
{
    int a[20],n,t,p,i;
    cout<<"\nEnter number of elements :";
    cin>>n;
    cout<<"\nAs binary search algorithm works in sorted array!";
    cout<<"\nEnter "<< n <<" values in ascending order : ";
    for(i=0;i<n;i++)
    cin>>a[i];
    cout<<"\nEnter the element to find : ";
    cin>>t;
    p=bin(a,n,t);
    if(p!=-1)
    cout<<"\nThe element is found at "<<p+1<<" position";
    else
    cout<<"\nElement Not Found!!";
    system("pause");
    return 0;
}


Screenshot:
C++ Program Code to perform binary search on an array of elements, which is arranged in ascending order

0 comments: