Created
February 9, 2015 15:43
-
-
Save NathanEpstein/abbe91f2ca796a6af81a to your computer and use it in GitHub Desktop.
binary search in C++
This file contains hidden or 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 <vector> | |
#include <math.h> | |
#include <iostream> | |
using namespace std; | |
//get the index of a target integer from a sorted vector | |
int binSearch(const vector<int>& sorted, const int target){ | |
const int mid = floor(sorted.size()/2); | |
if (sorted[mid] == target){ | |
//return if it matches | |
return mid; | |
} | |
else if (sorted[mid] > target){ | |
//search left | |
const vector<int> left(sorted.begin(),sorted.begin()+mid); | |
return binSearch(left, target); | |
} | |
else{ | |
//search right | |
const vector<int> right(sorted.begin()+mid,sorted.end()); | |
return (mid + binSearch(right, target)); | |
} | |
} | |
int main(){ | |
vector<int> v; | |
for (int i=0; i<50; i++){ | |
v.push_back(2*i); | |
} | |
int result = binSearch(v,14); //expect the answer to be 7 | |
cout<<(result == 7)<<'\n'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment