Skip to content

Commit aee0f61

Browse files
Merge pull request #447 from sakshamsachdeva/master
Binary Search in Kotlin #445
2 parents ef18bf6 + 20150b0 commit aee0f61

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Kotlin/BinarySearch.kt

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
fun 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 = binarySearchRecursive(input, eleToSearch, 0, input.size -1)
5+
if(pos >= 0 ) {
6+
println(pos) // to print position at last
7+
} else {
8+
println("Position not found")
9+
}
10+
}
11+
12+
fun binarySearchRecursive(input: IntArray, eleToSearch: Int, low:Int, high:Int): Int {
13+
14+
while(low <=high) {
15+
val mid = (low + high) /2
16+
when {
17+
eleToSearch > input[mid] -> return binarySearchRecursive(input, eleToSearch, mid+1, high) // element is greater than middle element of array, so it will be in right half. Recursion will call the right half again
18+
eleToSearch < input[mid] -> return binarySearchRecursive(input, eleToSearch, low, mid-1) //element is less than middle element of array, so it will be in left half of the array. Recursion will call the left half again.
19+
eleToSearch == input[mid] -> return mid // element found.
20+
}
21+
}
22+
return -1
23+
}

0 commit comments

Comments
 (0)