RosettaCodeData/Task/Binary-search/Kotlin/binary-search.kotlin

39 lines
1.3 KiB
Text
Raw Permalink Normal View History

2017-09-23 10:01:46 +02:00
fun <T : Comparable<T>> Array<T>.iterativeBinarySearch(target: T): Int {
2016-12-05 22:15:40 +01:00
var hi = size - 1
var lo = 0
while (hi >= lo) {
val guess = lo + (hi - lo) / 2
2017-09-23 10:01:46 +02:00
if (this[guess] > target) hi = guess - 1
else if (this[guess] < target) lo = guess + 1
else return guess
2016-12-05 22:15:40 +01:00
}
return -1
}
2017-09-23 10:01:46 +02:00
fun <T : Comparable<T>> Array<T>.recursiveBinarySearch(target: T, lo: Int, hi: Int): Int {
if (hi < lo) return -1
2016-12-05 22:15:40 +01:00
val guess = (hi + lo) / 2
2017-09-23 10:01:46 +02:00
return if (this[guess] > target) recursiveBinarySearch(target, lo, guess - 1)
else if (this[guess] < target) recursiveBinarySearch(target, guess + 1, hi)
else guess
2016-12-05 22:15:40 +01:00
}
fun main(args: Array<String>) {
2017-09-23 10:01:46 +02:00
val a = arrayOf(1, 3, 4, 5, 6, 7, 8, 9, 10)
var target = 6
var r = a.iterativeBinarySearch(target)
println(if (r < 0) "$target not found" else "$target found at index $r")
target = 250
r = a.iterativeBinarySearch(target)
println(if (r < 0) "$target not found" else "$target found at index $r")
2016-12-05 22:15:40 +01:00
2017-09-23 10:01:46 +02:00
target = 6
r = a.recursiveBinarySearch(target, 0, a.size)
println(if (r < 0) "$target not found" else "$target found at index $r")
target = 250
r = a.recursiveBinarySearch(target, 0, a.size)
println(if (r < 0) "$target not found" else "$target found at index $r")
2016-12-05 22:15:40 +01:00
}