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