-
-
Notifications
You must be signed in to change notification settings - Fork 398
/
Copy pathBinarySearch.scala
83 lines (72 loc) · 2.03 KB
/
BinarySearch.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package Search
/** An implementation of binary search algorithm to search an element in a sorted list
*/
import scala.annotation.tailrec
object BinarySearch {
/** @param arr
* - a sequence of integers
* @param elem
* - a integer to search for in the @args
* @return
* - index of the @elem otherwise -1
*/
def binarySearch(arr: List[Int], elem: Int): Int = {
binarySearch(arr, elem, 0, arr.length)
}
/** @param arr
* - a sequence of integers
* @param elem
* - a integer to search for in the @args
* @param fromIndex
* - the index of the first element (inclusive) to be searched
* @param toIndex
* - toIndex the index of the last element (exclusive) to be searched
* @return
* - index of the @elem otherwise -1
*/
def binarySearch(arr: List[Int], elem: Int, fromIndex: Int, toIndex: Int): Int = {
@tailrec
def SearchImpl(lo: Int, hi: Int): Int = {
if (lo > hi)
-1
else {
val mid: Int = lo + (hi - lo) / 2
arr(mid) match {
case mv if (mv == elem) => mid
case mv if (mv <= elem) => SearchImpl(mid + 1, hi)
case _ => SearchImpl(lo, mid - 1)
}
}
}
SearchImpl(fromIndex, toIndex - 1)
}
/** @param arr
* - a sequence of integers
* @param elem
* - a integer to search for in the @args
* @return
*/
def lowerBound(arr: List[Int], elem: Int): Int = {
lowerBound(arr, elem, 0, arr.length - 1)
}
/** @param arr
* - a sequence of integers
* @param elem
* - a integer to search for in the @args
* @param lo
* - lowest value index
* @param hi
* - highest value index
* @return
*/
def lowerBound(arr: List[Int], elem: Int, lo: Int, hi: Int): Int = {
if (lo == hi) lo
else {
val m: Int = lo + (hi - lo) / 2
arr(m) match {
case mv if (mv < elem) => lowerBound(arr, elem, m + 1, hi)
case mv if (mv >= elem) => lowerBound(arr, elem, lo, m)
}
}
}
}