Skip to content

Instantly share code, notes, and snippets.

@MNoorFawi
Created August 3, 2020 01:14
Show Gist options
  • Save MNoorFawi/52c8757757e9a375f1767b6e811252d7 to your computer and use it in GitHub Desktop.
Save MNoorFawi/52c8757757e9a375f1767b6e811252d7 to your computer and use it in GitHub Desktop.
Range Binary Search in C
void range_binary_search(int *array, int len, int val, int *res) {
int right = 0;
int left = 0;
int middle;
// not found
if(val < array[0] || val > array[len - 1]){
right = 0;
left = -1;
}
// found
else{
while(right < len){
middle = (right + len) / 2;
if(val < array[middle])
len = middle;
else
right = middle + 1;
}
len = right - 1;
while(left < len){
middle = (left + len) / 2;
if(val > array[middle])
left = middle + 1;
else
len = middle;
}
}
res[0] = left;
res[1] = right - 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment