fun binarySearch(array: List<Int>, number: Int, left: Int, right: Int): Int {
if(left == right && array[left] == number) {
return left
}
else if (left >= right) {
return -1
}
val middle = (left + right) / 2
if (number < array[middle]) {
return binarySearch(array, number, left, middle)
} else if (number > array[middle]) {
return binarySearch(array, number, middle + 1, right)
} else {
return middle
}
}
fun main() {
val array = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val number = 8
val index = binarySearch(array, number, 0, array.count())
if (index == -1) {
println("Szukanej liczby nie ma na liscie")
} else {
println("Szukana liczba znajduje sie pod indeksem $index")
}
}
ZnVuIGJpbmFyeVNlYXJjaChhcnJheTogTGlzdDxJbnQ+LCBudW1iZXI6IEludCwgbGVmdDogSW50LCByaWdodDogSW50KTogSW50IHsKICBpZihsZWZ0ID09IHJpZ2h0ICYmIGFycmF5W2xlZnRdID09IG51bWJlcikgewogICAgcmV0dXJuIGxlZnQKICB9CiAgZWxzZSBpZiAobGVmdCA+PSByaWdodCkgewogICAgcmV0dXJuIC0xCiAgfQoKICB2YWwgbWlkZGxlID0gKGxlZnQgKyByaWdodCkgLyAyCgogIGlmIChudW1iZXIgPCBhcnJheVttaWRkbGVdKSB7CiAgICByZXR1cm4gYmluYXJ5U2VhcmNoKGFycmF5LCBudW1iZXIsIGxlZnQsIG1pZGRsZSkKICB9IGVsc2UgaWYgKG51bWJlciA+IGFycmF5W21pZGRsZV0pIHsKICAgIHJldHVybiBiaW5hcnlTZWFyY2goYXJyYXksIG51bWJlciwgbWlkZGxlICsgMSwgcmlnaHQpCiAgfSBlbHNlIHsKICAgIHJldHVybiBtaWRkbGUKICB9Cn0KCmZ1biBtYWluKCkgewogIHZhbCBhcnJheSA9IGxpc3RPZigxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5LCAxMCkKICB2YWwgbnVtYmVyID0gOAoKICB2YWwgaW5kZXggPSBiaW5hcnlTZWFyY2goYXJyYXksIG51bWJlciwgMCwgYXJyYXkuY291bnQoKSkKCiAgaWYgKGluZGV4ID09IC0xKSB7CiAgICBwcmludGxuKCJTenVrYW5laiBsaWN6YnkgbmllIG1hIG5hIGxpc2NpZSIpCiAgfSBlbHNlIHsKICAgIHByaW50bG4oIlN6dWthbmEgbGljemJhIHpuYWpkdWplIHNpZSBwb2QgaW5kZWtzZW0gJGluZGV4IikKICB9Cn0=