Skip to content

Instantly share code, notes, and snippets.

@lnikon
Created June 27, 2018 11:48
Show Gist options
  • Save lnikon/a235ada85121c090c17e0aa9759ed5c7 to your computer and use it in GitHub Desktop.
Save lnikon/a235ada85121c090c17e0aa9759ed5c7 to your computer and use it in GitHub Desktop.
Binary Search Implementation
#include <vector>
#include <iostream>
#include <utility>
template <class T>
auto binarySearch(std::vector<T>& vec, const T& key)
{
size_t left = 0;
size_t right = vec.size() + 1;
size_t middle = (left + right) / 2;
while(left <= right)
{
if(vec[middle] == key)
{
return std::pair<bool, size_t>(true, middle);
}
if(vec[middle] < key)
{
left = middle - 1;
}
else
{
right = middle + 1;
}
middle = (left + right) / 2;
}
return std::pair<bool, size_t>(false, 0);
}
int main()
{
std::vector<int> vec {1, 4, 3, 6, 2, -3, 4, -1, 0};
auto exist_pair = binarySearch<decltype(vec)::value_type>(vec, -3);
if(exist_pair.first)
{
std::cout << "Index: #" << exist_pair.second
<< " : Item: " << vec[exist_pair.second] << "\n";
}
else
{
std::cout << "Couldn't find Item\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment