From 37b619725dbb5e674bfc4dae32a96b0a41ee7d87 Mon Sep 17 00:00:00 2001 From: yangchuz Date: Tue, 30 Oct 2018 16:25:08 +0800 Subject: [PATCH 1/2] Binary search non-recursive implementation --- scala/15_bsearch/BSearch.scala | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 scala/15_bsearch/BSearch.scala diff --git a/scala/15_bsearch/BSearch.scala b/scala/15_bsearch/BSearch.scala new file mode 100644 index 0000000..0c8d0b4 --- /dev/null +++ b/scala/15_bsearch/BSearch.scala @@ -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 + } +} From 44a2376207e4dfc79e8c55e029b1048cbddaa571 Mon Sep 17 00:00:00 2001 From: yangchuz Date: Tue, 30 Oct 2018 16:27:06 +0800 Subject: [PATCH 2/2] Binary search recursive implementation --- scala/15_bsearch/BSearchRecursive.scala | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 scala/15_bsearch/BSearchRecursive.scala diff --git a/scala/15_bsearch/BSearchRecursive.scala b/scala/15_bsearch/BSearchRecursive.scala new file mode 100644 index 0000000..b14a706 --- /dev/null +++ b/scala/15_bsearch/BSearchRecursive.scala @@ -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 + } + } +}