Curious to know how I can improve it, especially the pattern matching part seems a bit repetitive at the moment (lots of case x if ds(x)
)
def binarySearch(ds: Array[Double], key: Double): Int = {
@annotation.tailrec
def go(low: Int, mid: Int, high: Int): Int = {
mid match {
case x if ds(x) == key => x
case x if high <= low => -1
case x if ds(x) < key => go(mid + 1, (high - mid + 1) / 2 + mid, high)
case x if ds(x) > key => go(low, (mid - low) / 2 + low, mid - 1)
}
}
ds.size match {
case 0 => -1
case _ => go(0, ds.size / 2, ds.size - 1)
}
}