From e8e42696b14e27fa9817e30e3182147435575f64 Mon Sep 17 00:00:00 2001 From: Manik Fernando Date: Wed, 4 Oct 2017 12:15:37 +0530 Subject: [PATCH 1/3] Added recursive binary search in scala --- .../binary_search/scala/binary_search.scala | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 search/binary_search/scala/binary_search.scala diff --git a/search/binary_search/scala/binary_search.scala b/search/binary_search/scala/binary_search.scala new file mode 100644 index 0000000000..ceba97c692 --- /dev/null +++ b/search/binary_search/scala/binary_search.scala @@ -0,0 +1,24 @@ + + + +def binary_search(lst:Array[Int],l:Int,r:Int,num:Int):Int={ + + if(l <= r){ + val mid = l+(r-1)/2 + + if (lst(mid) == num) return mid else + if (lst(mid) < num ) return binary_search(lst,mid+1,r,num) else + return binary_search(lst,l,mid-1,num) + + } + + + return -1 +} + +def test(){ + + val l = Array(12,3,4,5,6,7) + + assert(binary_search(l,1,l.length,4) == 2) +} \ No newline at end of file From 3ba255514ad8c161d7250f86697cc0bc1207f9f1 Mon Sep 17 00:00:00 2001 From: Manik Fernando Date: Wed, 4 Oct 2017 12:26:26 +0530 Subject: [PATCH 2/3] Added docstring --- search/binary_search/scala/binary_search.scala | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/search/binary_search/scala/binary_search.scala b/search/binary_search/scala/binary_search.scala index ceba97c692..a0e28101b1 100644 --- a/search/binary_search/scala/binary_search.scala +++ b/search/binary_search/scala/binary_search.scala @@ -1,6 +1,13 @@ - +/** +* Recursive binary search algorithm +* @param lst the integer array which is being searched +* @param l lower value for partition +* @param r upper value for partition +* @param num number which is being searched for +* @return the index of the element that matches the search term, returns -1 if not found +*/ def binary_search(lst:Array[Int],l:Int,r:Int,num:Int):Int={ if(l <= r){ From b47bfe7c8dbf17ba67a54dcb0fc021e70afd67cc Mon Sep 17 00:00:00 2001 From: Manik Fernando Date: Wed, 4 Oct 2017 13:04:38 +0530 Subject: [PATCH 3/3] linear search implemented recursively in scala --- search/linear_search/scala/linear_search.scala | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 search/linear_search/scala/linear_search.scala diff --git a/search/linear_search/scala/linear_search.scala b/search/linear_search/scala/linear_search.scala new file mode 100644 index 0000000000..bfd26def28 --- /dev/null +++ b/search/linear_search/scala/linear_search.scala @@ -0,0 +1,16 @@ +/** +* Recursive linear search implemented in scala +* unnecessarily complex +*/ +def linear_search(lst:Array[Int],idx:Int,key:Int):Int={ + if(lst.length == 0 ) return -1 else + if(lst(idx) == key) return idx else + return linear_search(lst,idx+1,key) +} + +def test(){ + + val l = Array(12,3,4,5,6,7) + + assert(linear_search(l,0,4) == 2) +} \ No newline at end of file