add binary search on kotlin
This commit is contained in:
committed by
Aditya Bhargava
parent
9723ed03cf
commit
f47666f099
21
01_introduction_to_algorithms/kotlin/BinarySearch.kt
Normal file
21
01_introduction_to_algorithms/kotlin/BinarySearch.kt
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
fun List<Int>.binarySearch(item: Int) : Int? {
|
||||||
|
var min = 0
|
||||||
|
var max = lastIndex
|
||||||
|
while (min <= max) {
|
||||||
|
val mid = (min + max)/2
|
||||||
|
val guess = this[mid]
|
||||||
|
if (guess == item) return mid
|
||||||
|
if (guess > item) max = mid -1
|
||||||
|
else min = mid + 1
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
val sortedArray = (0..100 step 3).toList()
|
||||||
|
|
||||||
|
|
||||||
|
fun main(args: Array<String>) {
|
||||||
|
print(sortedArray.binarySearch(6))
|
||||||
|
}
|
||||||
|
|
||||||
Reference in New Issue
Block a user