Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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