Created
July 31, 2020 18:49
-
-
Save danielchalef/85420ecb5370aa8552993b848c7e1717 to your computer and use it in GitHub Desktop.
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
import scala.annotation.tailrec | |
object bisect { | |
/** | |
* Port of Python's bisect_right implemented using tail recursion. | |
* | |
* Return the index where to insert item x in Array A, assuming A is sorted. | |
* The return value is such that all e in a[:i] have e <= x, and all e in | |
* a[i:] have e > x. So if x already appears in the list, a.insert(x) will | |
* insert just after the rightmost x already there. | |
* Optional args lo (default 0) and hi (default len(a)) bound the | |
* slice of a to be searched. | |
*/ | |
def bisectRight(A: Array[Int], x: Int): Int = | |
bisectRight(A, x, 0, A.length) | |
@tailrec | |
private def bisectRight(A: Array[Int], | |
x: Int, | |
lo: Int, | |
hi: Int): Int = { | |
if (lo < hi) { | |
val mid: Int = (lo + hi) / 2 | |
if (x < A(mid)) { | |
bisectRight(A, x, lo, mid) | |
} else { | |
bisectRight(A, x, mid + 1, hi) | |
} | |
} else lo | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment