Skip to content

Instantly share code, notes, and snippets.

@marionette-of-u
Created November 3, 2012 11:55
Show Gist options
  • Select an option

  • Save marionette-of-u/4007163 to your computer and use it in GitHub Desktop.

Select an option

Save marionette-of-u/4007163 to your computer and use it in GitHub Desktop.
binary_search_in_vector
void binary_search_test(){
std::vector<double> vec = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 };
auto insert = [&](double value) -> bool{
if(vec.empty() || value < *vec.begin()){
vec.insert(vec.begin(), value);
return true;
}else if(*vec.rbegin() < value){
vec.insert(vec.end(), value);
return true;
}
std::size_t i = 0, j = vec.size();
while(true){
std::size_t n = (j - i) / 2;
std::size_t prime = i + n;
if(value < vec[prime]){
j = prime;
}else if(vec[prime] < value){
i = prime;
}else{
return false;
}
if(n == 0){ break; }
}
vec.insert(vec.begin() + (i + 1), value);
return true;
};
auto print_vec = [&]() -> void{
for(auto i : vec){
std::cout << i << ", ";
}
std::cout << std::endl;
};
insert(-0.5);
insert(0.5);
insert(4.0);
insert(3.0);
insert(3.5);
insert(6.5);
insert(128.0);
print_vec();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment