Last active
July 20, 2022 22:24
-
-
Save mbove77/0d393a3429cfe98cad3a4ada5bdce873 to your computer and use it in GitHub Desktop.
Binary search with recursion implemented in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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