forked from ZoranPandovski/al-go-rithms
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request ZoranPandovski#49 from manikTharaka/master
Binary search in Scala
- Loading branch information
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |