Binary search non-recursive implementation

This commit is contained in:
yangchuz 2018-10-30 16:25:08 +08:00 committed by GitHub
parent 66c64c532c
commit 37b619725d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,18 @@
object BSearch {
def search(nums: Array[Int], target: Int): Int = {
var low = 0
var high = nums.length - 1
while(low <= high){
val mid = low + ((high - low) >> 2)
if(nums(mid) > target){
high = mid - 1
} else if (nums(mid) < target){
low = mid + 1
} else {
return mid
}
}
return -1
}
}