Skip to content

Instantly share code, notes, and snippets.

@khondokerfahad
Last active January 31, 2020 19:21
Show Gist options
  • Save khondokerfahad/8623a2ef911029bfcee8ba25df21face to your computer and use it in GitHub Desktop.
Save khondokerfahad/8623a2ef911029bfcee8ba25df21face to your computer and use it in GitHub Desktop.
Binary search without build-in functioon
#include<bits/stdc++.h>
using namespace std;
bool bnry_srch(int f , int *v , int n){
int low = 0, high = n;
while(low<=high){
int c = (low+high)/2;
if(v[c]==f)
return true;
if(v[c]>f)
high = c-1;
else
low = c+1;
}
return false;
}
int main(){
int n , i , a;
cout << "Select the range :";
cin >> n;
int arr[n];
cout << "Input the array : ";
for(i=0; i<n; i++){
cin >> arr[i];
}
sort(arr,arr+n);
int f;
cout << "Number to search :";
cin >> f;
if(bnry_srch(f , arr , n))
cout << "Yes,it's in the array" << endl;
else
cout << "Not in the array by binary search" << endl;
}
/*For build-in binary_search function::::::::::
-------------------------------------------------------------
if(binary_search(v.begin() , v.end() , f))
cout << "It's in a vector" << endl;
else
cout << "Not in the vector" << endl;
-------------------------------------------------------------
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment