Skip to content

Commit ea466e4

Browse files
authored
Kotlin 704-Binary-Search
1 parent ef902eb commit ea466e4

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

kotlin/704-Binary-Search.kt

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
// Easy solution
3+
/*
4+
fun search(nums: IntArray, target: Int): Int {
5+
return nums.indexOf(target)
6+
}
7+
*/
8+
9+
// Recursive solution
10+
fun search(nums: IntArray, target: Int): Int {
11+
return searchAux(nums, target, 0, nums.size - 1)
12+
}
13+
14+
private fun searchAux(nums: IntArray, target: Int, begin: Int, end: Int): Int {
15+
if (begin > end) return -1
16+
17+
val mid: Int = (begin + end) / 2
18+
19+
return if (nums[mid] == target) mid
20+
else if (nums[mid] > target) searchAux(nums, target, begin, mid - 1)
21+
else searchAux(nums, target, mid + 1, end)
22+
}
23+
}

0 commit comments

Comments
 (0)