-
Notifications
You must be signed in to change notification settings - Fork 108
/
BinarySearch.kt
85 lines (75 loc) · 2.43 KB
/
BinarySearch.kt
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
84
85
package search
/**
*
* Binary search algorithm only works for sorted lists and arrays
*
* best time: 1
* worst time: log(n)
* amount of memory: 1
*
*/
class BinarySearch {
// searches for an element in the array and returns the index of the searched element or -1
fun <T : Comparable<T>> search(array: Array<T>, element: T) : Int {
if (array.isEmpty()) return -1
var left = 0
var right = array.size
while (left < right) {
val middle = left + (right - left) / 2
if (array[middle] < element) {
left = middle + 1
} else if (array[middle] > element) {
right = middle
} else {
return middle
}
}
return -1
}
// recursive method
// P.S. The tailrec modifier tells the compiler to optimize the recursion and turn it into an iterative version
tailrec fun <T : Comparable<T>> searchRecursive(array: Array<T>, element: T, left: Int = 0, right: Int = array.size - 1): Int {
if (left <= right) {
val middle = left + (right - left) / 2
if (array[middle] == element) {
return middle
}
return if (array[middle] > element) {
searchRecursive(array, element, left, middle - 1)
} else {
searchRecursive(array, element, middle + 1, right)
}
}
return -1
}
// finds the left border index to insert an element into a sorted array
fun <T : Comparable<T>> leftBound(array: Array<T>, element: T) : Int {
if (array.isEmpty()) return 0
var left = -1
var right = array.size
while ((right - left) > 1) {
val middle = left + (right - left) / 2
if (element > array[middle]) {
left = middle
} else {
right = middle
}
}
return left
}
// finds the right border index to insert an element into a sorted array
fun <T : Comparable<T>> rightBound(array: Array<T>, element: T) : Int {
if (array.isEmpty()) return -1
var left = -1
var right = array.size
while ((right - left) > 1) {
val middle = (right + left) / 2
if (element > array[middle]) {
left = middle
} else {
right = middle
}
}
return right
}
}