Program to Implement Binary Search in CPP (C plus plus)

Program to Implement Binary Search in CPP (C plus plus)

In this tutorial, we will learn about Program to Implement Binary Search in CPP (C plus plus).

#include<iostream>
 
using namespace std;
 
int main()
{
    int search(int [],int,int);
    int val;
	int i;
	int array[100];
	int j;
	int bal;
	
    cout<<"Please enter the number of values: ";
    cin>>val;
    
    cout<<endl<<"Please enter values into array: "<<endl;
    
    for(i=0;i<val;++i)
    {
        cin>>array[i];
    }
    
    cout<<endl<<"Please enter value to search: ";
    cin>>j;
    
    bal=search(array,val,j);
    
    if(bal!=-1)
        cout<<endl<<"Entered value found at position "<<bal+1;
    else
        cout<<endl<<"Value not found!";
 
    return 0;
}
 
int search(int array[],int n,int e)
{
    int f;
	int l;
	int m;
	
    f=0;
    l=n-1;
    
    while(f<=l)
    {
        m=(f+l)/2;
        if(e==array[m])
            return(m);
            
        else
            if(e>array[m])
                f=m+1;
                
            else
                l=m-1;
    }
    
    return -1;
}

Output:

Program to Implement Binary Search in CPP (C plus plus)
Program to Implement Binary Search in CPP (C plus plus)
Prof.Fazal Rehman Shamil (Available for Professional Discussions)
1. Message on Facebook page for discussions,
2. Video lectures on Youtube
3. Email is only for Advertisement/business enquiries.