Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save felipealbrecht/7c4532da2d06f06a633c to your computer and use it in GitHub Desktop.
Save felipealbrecht/7c4532da2d06f06a633c to your computer and use it in GitHub Desktop.
Binary search of the find_first_ocorrece_where_value_is_higher
#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