Skip to content

Instantly share code, notes, and snippets.

@ioab
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save ioab/d8121d541bf4e25fffc5 to your computer and use it in GitHub Desktop.

Select an option

Save ioab/d8121d541bf4e25fffc5 to your computer and use it in GitHub Desktop.
BinarySearch Algorithm
/**
* @note:
* Works properly with numbers.
* other types may have to define another equality criteria.
*
* @return: Item index if found. -1 otherwise.
*/
template<typename T>
int BinarySearch(T * arr, int size, T searchKey)
{
int first = 0,
last = size - 1,
m = 0; // middle
while (first <= last)
{
m = (first + last) / 2;
if (arr[m] == searchKey)
{
return m;
}
else if (arr[m] < searchKey)
{
first = m + 1;
}
else
{
last = m - 1;
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment