Kotlin - Completed Binary Search
This commit is contained in:
parent
d2abc4180e
commit
568e69fe4d
1 changed files with 20 additions and 0 deletions
20
kotlin/binary-search/src/main/kotlin/BinarySearch.kt
Normal file
20
kotlin/binary-search/src/main/kotlin/BinarySearch.kt
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
class BinarySearch {
|
||||||
|
companion object {
|
||||||
|
fun search(inpList: List<Int>, searchElement: Int): Int {
|
||||||
|
require(inpList.sorted() == inpList)
|
||||||
|
var leftBound = 0
|
||||||
|
var rightBound = inpList.size - 1
|
||||||
|
while (leftBound <= rightBound){
|
||||||
|
val middle = Math.floor(((leftBound + rightBound)/2).toDouble()).toInt()
|
||||||
|
if (inpList[middle] < searchElement){
|
||||||
|
leftBound = middle + 1
|
||||||
|
}
|
||||||
|
else if (inpList[middle] > searchElement){
|
||||||
|
rightBound = middle - 1
|
||||||
|
}
|
||||||
|
else return middle
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Add table
Reference in a new issue