Skip to content

Commit

Permalink
Merge pull request wangzheng0822#127 from yangchuz/master
Browse files Browse the repository at this point in the history
Basic binary search implementation in Scala
  • Loading branch information
wangzheng0822 authored Nov 2, 2018
2 parents b0a8643 + 44a2376 commit 3531564
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
18 changes: 18 additions & 0 deletions scala/15_bsearch/BSearch.scala
Original file line number Diff line number Diff line change
@@ -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 changes: 20 additions & 0 deletions scala/15_bsearch/BSearchRecursive.scala
Original file line number Diff line number Diff line change
@@ -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
}
}
}

0 comments on commit 3531564

Please sign in to comment.