Created
June 9, 2023 19:14
-
-
Save AssortedFantasy/d122a153797f3a02d108c2af2e21c428 to your computer and use it in GitHub Desktop.
C Upper and Lower Bound Implementations
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
/* | |
Upper and lower bounds. | |
Upper bound: First where target < array[i] | |
Lower bound: First where !(array[i] < target) | |
Assume a 3 way comparision returns this. | |
[-1 -1 -1 -1 0 0 0 0 0 1 1 1 1 1] | |
^ Lower bound. ^ | |
Upper bound. | |
*/ | |
// Upper bound | |
int hi = array_size; | |
int lo = 0; | |
while (hi > lo) { | |
const int mid = lo + (hi-lo)/2; | |
if (target < array[mid]) { | |
hi = mid; | |
} else { | |
lo = mid + 1; | |
} | |
} | |
const int upper_bound = lo; | |
// Lower bound. | |
int hi = array_size; | |
int lo = 0; | |
while (hi > lo) { | |
const int mid = lo + (hi-lo)/2; | |
if (array[mid] < target) { | |
lo = mid + 1; | |
} else { | |
hi = mid; | |
} | |
} | |
const int lower_bound = lo; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good for leetcode problems.