Last active
December 12, 2015 18:55
-
-
Save felipealbrecht/7c4532da2d06f06a633c to your computer and use it in GitHub Desktop.
Binary search of the find_first_ocorrece_where_value_is_higher
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> | |
typedef std::vector<int> Array; | |
int find_first_ocorrece_where_value_is_higher(Array& a, int value); | |
int main() { | |
Array v = {0, 10, 20, 30, 40, 50}; | |
int pos = find_first_ocorrece_where_value_is_higher(v, 25); | |
std::cerr << pos << " - " << v[pos] << std::endl; // 3, 30 | |
return 0; | |
} | |
int find_first_ocorrece_where_value_is_higher(Array& a, int value) { | |
int min = 0; | |
int max = a.size(); | |
while (min != max) { | |
int med = (min + max) / 2; // attention with overflow | |
if (a[med] <= value) { | |
min = med + 1; | |
} else { | |
max = med; | |
} | |
} | |
return min - 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment