Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions kotlin-programs/binary_search.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class BinarySearch {
fun doBinarySearch () {
println("Please, enter some integer numbers using space bar")
val inputList = readLine()!!.split(' ').map(String::toInt)
val listSorted = inputList.sorted()
println("Please, enter the number you want to find")
val item = readLine()!!.toInt()
var low = 0
var high = listSorted.size - 1
var stepCount = 0
var isItemFound = false
while (low <= high) {
val mid = (low + high) / 2
val guess = listSorted[mid]
stepCount++
when {
guess == item -> {
println("Your number $item was found in $stepCount steps")
isItemFound = true
}
guess > item -> high = mid -1
else -> low = mid + 1
}
if (isItemFound) break //"break" is not allowed in "when" statement
}
if (!isItemFound) {
println("Your number wasn't found")
}
}
}