Last active
June 11, 2019 15:01
-
-
Save junaidrahim/def1907b80e1e9a09bc50e5aa0c48627 to your computer and use it in GitHub Desktop.
Binary Search
This file contains 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 <vector> | |
#include "../include/binary_search.hpp" | |
int binary_search(std::vector<int> array, int x){ | |
int l = 0; | |
int r = array.size() - 1; | |
while (l <= r) { | |
int m = (l + r) / 2; | |
if (array[m] == x) | |
return m; | |
if (array[m] < x) | |
l = m + 1; | |
else | |
r = m - 1; | |
} | |
return -1; // not found | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment