Skip to content

Instantly share code, notes, and snippets.

@yberreby
Created September 11, 2014 11:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yberreby/a0417377cc9aa633778d to your computer and use it in GitHub Desktop.
Save yberreby/a0417377cc9aa633778d to your computer and use it in GitHub Desktop.
Binary search implementation for native arrays
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
int binary_search(const T& elem, const T* a, const size_t length) {
int middleIndex = length / 2;
T midpoint = a[middleIndex];
if (midpoint == elem) return middleIndex;
if (midpoint > elem) {
return binary_search(elem, a, middleIndex);
}
if (midpoint < elem) {
return binary_search(elem, a + middleIndex, length - middleIndex);
}
return -1;
}
template <typename T, size_t length>
int find(const T& elem, const T (&a)[length]) { return binary_search<T>(elem, a, length); }
int main() {
int array[] = {-5,3,4,6,8,9,14};
cout << find(6, array);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment