Last active
December 21, 2015 06:08
-
-
Save k06a/6261834 to your computer and use it in GitHub Desktop.
Binary search template function with searching nearest greater.
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
template<typename TI, typename TV> | |
int BinSearch(TI begin, TI end, TV value) | |
{ | |
int minIndex = 0; | |
int maxIndex = end - begin - 1; | |
while (minIndex <= maxIndex) | |
{ | |
int midIndex = (minIndex + maxIndex) / 2; | |
TI comparison = begin + midIndex; | |
if ((TV)*comparison == value) | |
return midIndex; | |
if ((TV)*comparison < value) | |
minIndex = midIndex + 1; | |
else | |
maxIndex = midIndex - 1; | |
} | |
return ~minIndex; | |
} | |
template<typename TI, typename TV> | |
int BinSearchNearestGr(TI begin, TI end, TV value) | |
{ | |
int index = BinSearch(begin, end, value); | |
return (index < 0) ? ~index : index; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment