Merge pull request #127 from yangchuz/master
Basic binary search implementation in Scala
This commit is contained in:
commit
3531564225
18
scala/15_bsearch/BSearch.scala
Normal file
18
scala/15_bsearch/BSearch.scala
Normal 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
|
||||||
|
}
|
||||||
|
}
|
20
scala/15_bsearch/BSearchRecursive.scala
Normal file
20
scala/15_bsearch/BSearchRecursive.scala
Normal 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user