Skip to content

Instantly share code, notes, and snippets.

@counter2015
Created May 17, 2019 07:34
Show Gist options
  • Save counter2015/2b9e3bcf46c888f0298d9aef69115acd to your computer and use it in GitHub Desktop.
Save counter2015/2b9e3bcf46c888f0298d9aef69115acd to your computer and use it in GitHub Desktop.
functional style of binary search
def binarySearchFunctional(list: Array[Int], target: Int): Int = {
def bsf(list: Array[Int], target: Int, start: Int, end: Int): Int = {
if (start>end) return -1
val mid = start + (end-start+1)/2
list match {
case (arr:Array[Int]) if (arr(mid)==target) => mid
case (arr:Array[Int]) if (arr(mid)>target) => bsf(list, target, start, mid-1)
case (arr:Array[Int]) if (arr(mid)<target) => bsf(list, target, mid+1, end)
}
}
bsf(list, target, 0, list.length-1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment