Skip to content

Commit

Permalink
[lib/util] Added binary search functions in Ranges.v3 (#288)
Browse files Browse the repository at this point in the history
  • Loading branch information
linxuanm authored Oct 11, 2024
1 parent 97a72ba commit 3afb109
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions lib/util/Ranges.v3
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,40 @@ component Ranges {
}
return i;
}
// Performs binary search and returns the index.
def binarySearch<T>(range: Range<T>, val: T, lt: (T, T) -> bool) -> int {
var l = 0, r = range.length;
while (l < r) {
var mid = (l + r) >> 1;
var mid_val = range[mid];
if (lt(val, mid_val)) r = mid - 1;
else if (lt(mid_val, val)) l = mid + 1;
else return mid;
}
return -1;
}
// Returns the *first* element that is *not less* than `val` in a sorted range.
def lowerbound<T>(range: Range<T>, val: T, lt: (T, T) -> bool) -> int {
var start = 0;
var count = range.length;
while (count > 0) {
var step = count >> 1;
var mid = start + step;
if (lt(range[mid], val)) { start = mid + 1; count -= step + 1; }
else count = step;
}
return start;
}
// Returns the *first* element that is *greater* than `val` in a sorted range.
def upperbound<T>(range: Range<T>, val: T, lt: (T, T) -> bool) -> int {
var start = 0;
var count = range.length;
while (count > 0) {
var step = count >> 1;
var mid = start + step;
if (!lt(val, range[mid])) { start = mid + 1; count -= step + 1; }
else count = step;
}
return start;
}
}

0 comments on commit 3afb109

Please sign in to comment.