Created
May 17, 2019 07:34
-
-
Save counter2015/2b9e3bcf46c888f0298d9aef69115acd to your computer and use it in GitHub Desktop.
functional style of binary search
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
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