Skip to content

Instantly share code, notes, and snippets.

@paullewallencom
Last active July 31, 2018 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paullewallencom/2ae0030ab62b9e055a1c842ed027bb12 to your computer and use it in GitHub Desktop.
Save paullewallencom/2ae0030ab62b9e055a1c842ed027bb12 to your computer and use it in GitHub Desktop.
C++ Binary Search
#include <iostream>
#include <vector>
using namespace std;
const int NOT_FOUND = -1;
template <typename Comparable>
int binarySearch( const vector<Comparable> & a, const Comparable & x )
{
int low = 0, high = a.size( ) - 1;
while( low <= high )
{
int mid = ( low + high ) / 2;
if( a[ mid ] < x )
low = mid + 1;
else if( a[ mid ] > x )
high = mid - 1;
else
return mid; // Found
}
return NOT_FOUND; // NOT_FOUND is defined as -1
}
int main( )
{
const int SIZE = 8;
vector<int> a( SIZE );
for( int i = 0; i < SIZE; ++i )
a[ i ] = i * 2;
for( int j = 0; j < SIZE * 2; ++j )
cout << "Found " << j << " at " << binarySearch( a, j ) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment