Issue
I wrote this function with recursion in Kotlin, it's just for academic purposes.
But I have a problem, when the condition is true, the execution is not interrupted. It's as if it ignores the return command and keeps iterating.
I have seen it in debug, that when the condition is true it goes through there and then continues.
Anyone knows how to solve this?
In this capture, see the debugger in the return true statement, but the function don't exit.
Here is the function:
// 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
}
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
}
Here is the call:
val result = binarySearch(arrayOf(1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,17,18,19,20,21,22,23), 16)
Solution
You need to return the result of the recursion, like
return binarySearch(inputArray.copyOfRange(inputArray.size / 2, inputArray.size), itemToSearch)
so in total:
// 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
}
if (itemToSearch > inputArray[(inputArray.size / 2) - 1]) {
return binarySearch(inputArray.copyOfRange(inputArray.size / 2, inputArray.size), itemToSearch)
} else {
return binarySearch(inputArray.copyOfRange(0, inputArray.size / 2), itemToSearch)
}
}
return false
}
Answered By - Ivo Beckers
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.