Skip to content

Commit

Permalink
Merge pull request ZoranPandovski#49 from manikTharaka/master
Browse files Browse the repository at this point in the history
Binary search in Scala
  • Loading branch information
ZoranPandovski authored Oct 4, 2017
2 parents 304dddc + b47bfe7 commit 34bc5fe
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
31 changes: 31 additions & 0 deletions search/binary_search/scala/binary_search.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@


/**
* 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){
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)
}
16 changes: 16 additions & 0 deletions search/linear_search/scala/linear_search.scala
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit 34bc5fe

Please sign in to comment.