Skip to content

Instantly share code, notes, and snippets.

@junaidrahim
Last active June 11, 2019 15:01
Show Gist options
  • Save junaidrahim/def1907b80e1e9a09bc50e5aa0c48627 to your computer and use it in GitHub Desktop.
Save junaidrahim/def1907b80e1e9a09bc50e5aa0c48627 to your computer and use it in GitHub Desktop.
Binary Search
#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