Created
October 27, 2018 09:39
-
-
Save patelpreet422/2c4189a872943c82921452ebcfe370bc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <algorithm> | |
#include <vector> | |
using namespace std; | |
bool binary_search(vector<int>::iterator lower, vector<int>::iterator upper, int k) | |
{ | |
auto mid = next(lower, distance(lower, upper)/2); | |
while(lower <= upper) | |
{ | |
if(*mid == k) return true; | |
else if(* mid < k) | |
{ | |
lower = next(mid); | |
} else { | |
upper = prev(mid); | |
} | |
mid = next(lower, distance(lower, upper)/2); | |
} | |
return false; | |
} | |
int main() | |
{ | |
vector<int> vec{-7, 5, 0, -5, 10, 50}; | |
sort(begin(vec), end(vec)); | |
cout << boolalpha << binary_search(begin(vec), end(vec), 10) << '\n'; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment