Skip to content

Instantly share code, notes, and snippets.

@mbove77
Last active July 20, 2022 22:24
Show Gist options
  • Save mbove77/0d393a3429cfe98cad3a4ada5bdce873 to your computer and use it in GitHub Desktop.
Save mbove77/0d393a3429cfe98cad3a4ada5bdce873 to your computer and use it in GitHub Desktop.
Binary search with recursion implemented in Kotlin
// The inputArray must be sorted in order to apply the binary search.
fun binarySearch(inputArray: Array<Int>, itemToSearch: Int) : Boolean {
// This print is for see the interactions in the search
println()
inputArray.forEach {
print("$it,")
}
if (inputArray.size > 1) {
if (itemToSearch == inputArray[(inputArray.size / 2) - 1]) {
return true
}
return if (itemToSearch > inputArray[(inputArray.size / 2) - 1]) {
binarySearch(inputArray.copyOfRange(inputArray.size / 2, inputArray.size), itemToSearch)
} else {
binarySearch(inputArray.copyOfRange(0, inputArray.size / 2), itemToSearch)
}
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment