Merge pull request #127 from yangchuz/master

Basic binary search implementation in Scala
This commit is contained in:
wangzheng0822 2018-11-02 10:49:58 +08:00 committed by GitHub
commit 3531564225
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 0 deletions

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
}
}

View File

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