Created
August 3, 2020 01:14
-
-
Save MNoorFawi/52c8757757e9a375f1767b6e811252d7 to your computer and use it in GitHub Desktop.
Range 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
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