Skip to content

Instantly share code, notes, and snippets.

@AssortedFantasy
Created June 9, 2023 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AssortedFantasy/d122a153797f3a02d108c2af2e21c428 to your computer and use it in GitHub Desktop.
Save AssortedFantasy/d122a153797f3a02d108c2af2e21c428 to your computer and use it in GitHub Desktop.
C Upper and Lower Bound Implementations
/*
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;
@AssortedFantasy
Copy link
Author

Good for leetcode problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment