I am trying to write a binary search algorithm to work with any data type that is defined to work with the relational operators and returns the position of the found element. I want to know if there is anything I need to be aware of when dealing with user defined types. As well as any flaws or improvements that I can make. Also one other question is how does my search compare to the built in binary_search function?
#include <iostream>
#include <iomanip>
#include <type_traits>
template<typename T, typename U>
U BinarySearch(T *arr, T toFind, U _size){ //make return type same as size for overflow issues
static_assert(std::is_integral<U>::value, "Integral type required for size of array");
U mid, low = 0, high = _size-1; //maintain same integral types
T m, l = arr[low], h = arr[high]; //maintain same T types
while(l<=toFind && h>=toFind){
mid = (high + low)/2;
m = arr[mid];
if(m > toFind){
h = arr[high = mid - 1];
}
else if(m < toFind){
l = arr[low = mid + 1];
}
else
return mid; //postion point + 1
}
//exits if not found
return -1;
}
const auto SIZE = 10;
int main()
{
double arr[SIZE] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.1};
auto pos = BinarySearch(arr, 1.1, SIZE);
std::cout << pos << '\n';
return 0;
}
Thanks for all your advice in advance.