Skip to content

Commit 72cb320

Browse files
Merge pull request #664 from sakshamsachdeva/master
binary_search_in_kotlin.kt
2 parents 4d47692 + cbfd8d0 commit 72cb320

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

Kotlin/binary_search_in_kotlin.kt

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
un main(args: Array<String>) {
2+
val input = readLine()!!.trim().split(" ").map { it -> it.toInt() }.toIntArray() // to read an array (from user input)
3+
val eleToSearch = readLine()!!.trim().toInt() // to read the element to be searched (from user input)
4+
val pos = binarySearchIterative(input, eleToSearch)
5+
if(pos >= 0 ) {
6+
println(pos) // to print position at last
7+
} else {
8+
println("Position not found")
9+
}
10+
}
11+
12+
fun binarySearchIterative(input: IntArray, eleToSearch: Int) : Int{
13+
var low = 0
14+
var high = input.size-1
15+
var mid:Int
16+
while(low <= high) {
17+
mid = (low + high)/2
18+
when {
19+
eleToSearch >input[mid] -> low = mid+1 // element is greater than middle element of array, so it will be in right half of array
20+
eleToSearch == input[mid] -> return mid // found the element
21+
eleToSearch < input[mid] -> high = mid-1 //element is less than middle element of array, so it will be in left half of the array.
22+
}
23+
}
24+
return -1
25+
}

0 commit comments

Comments
 (0)