patternModerate
Binary search in functional-style Scala
Viewed 0 times
searchscalastylebinaryfunctional
Problem
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 -1
case x if ds(x) 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)
}
}Solution
the
Could look like this
high high anyway you can as easily compute it inside your inner function and make the calls a bit more readable (only low and high)Could look like this
type Index = Int
def binarySearch(ds: Array[Double], key: Double): Option[Index] = {
@tailrec
def go(lo: Index, hi: Index): Option[Index] = {
if (lo > hi)
None
else {
val mid: Index = lo + (hi - lo) / 2
ds(mid) match {
case mv if (mv == key) => Some(mid)
case mv if (mv go(mid + 1, hi)
case _ => go(lo, mid - 1)
}
}
}
go(0, ds.size - 1)
}Code Snippets
type Index = Int
def binarySearch(ds: Array[Double], key: Double): Option[Index] = {
@tailrec
def go(lo: Index, hi: Index): Option[Index] = {
if (lo > hi)
None
else {
val mid: Index = lo + (hi - lo) / 2
ds(mid) match {
case mv if (mv == key) => Some(mid)
case mv if (mv <= key) => go(mid + 1, hi)
case _ => go(lo, mid - 1)
}
}
}
go(0, ds.size - 1)
}Context
StackExchange Code Review Q#55629, answer score: 10
Revisions (0)
No revisions yet.