Last active
May 4, 2020 06:44
-
-
Save vamsitallapudi/44f8fd1b86f5343306bf985112e2f390 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main.algorithms.searching | |
fun main(args: Array<String>) { | |
val input = readLine()!!.trim().split(" ").map { it -> it.toInt() }.toIntArray() // to read an array (from user input) | |
val eleToSearch = readLine()!!.trim().toInt() // to read the element to be searched (from user input) | |
val pos = binarySearchIterative(input, eleToSearch) | |
if(pos >= 0 ) { | |
println(pos) // to print position at last | |
} else { | |
println("Position not found") | |
} | |
} | |
fun binarySearchIterative(input: IntArray, eleToSearch: Int) : Int{ | |
var low = 0 | |
var high = input.size-1 | |
var mid:Int | |
while(low <= high) { | |
mid = low + ((high - low) / 2) | |
when { | |
eleToSearch >input[mid] -> low = mid+1 // element is greater than middle element of array, so it will be in right half of array | |
eleToSearch == input[mid] -> return mid // found the element | |
eleToSearch < input[mid] -> high = mid-1 //element is less than middle element of array, so it will be in left half of the array. | |
} | |
} | |
return -1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment