Created
September 11, 2014 11:26
-
-
Save yberreby/a0417377cc9aa633778d to your computer and use it in GitHub Desktop.
Binary search implementation for native arrays
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 <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