Skip to content

Instantly share code, notes, and snippets.

@Qiming-C
Created January 26, 2022 19:41
Show Gist options
  • Save Qiming-C/2ebd2effb5da213576995f0ad198b322 to your computer and use it in GitHub Desktop.
Save Qiming-C/2ebd2effb5da213576995f0ad198b322 to your computer and use it in GitHub Desktop.
binarySearch
def binarySearch(keys: Seq[Int],timestamp:Int): Int = {
val seq = keys.toSeq.sorted
var l = 0
var r = seq.size - 1
while (l <= r) {
val m = l + ((r - l) >> 1);
val p = seq(m)
if (p > timestamp) {
r = m - 1
} else {
l = m + 1
}
}
//this is used when not found the element, return the next value that is cloest to the given value
if (l > 0) seq(l - 1) else -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment