Last active
July 31, 2018 18:46
-
-
Save paullewallencom/2ae0030ab62b9e055a1c842ed027bb12 to your computer and use it in GitHub Desktop.
C++ Binary Search
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
#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