Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Kotlin 704-Binary-Search
  • Loading branch information
edo-ce authored Jul 21, 2022
commit ea466e48d4936c05553bfd854a8f7667ee25ad99
23 changes: 23 additions & 0 deletions kotlin/704-Binary-Search.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class Solution {
// Easy solution
/*
fun search(nums: IntArray, target: Int): Int {
return nums.indexOf(target)
}
*/

// Recursive solution
fun search(nums: IntArray, target: Int): Int {
return searchAux(nums, target, 0, nums.size - 1)
}

private fun searchAux(nums: IntArray, target: Int, begin: Int, end: Int): Int {
if (begin > end) return -1

val mid: Int = (begin + end) / 2

return if (nums[mid] == target) mid
else if (nums[mid] > target) searchAux(nums, target, begin, mid - 1)
else searchAux(nums, target, mid + 1, end)
}
}