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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
#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: