Skip to content

Instantly share code, notes, and snippets.

@vamsitallapudi
Last active May 4, 2020 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vamsitallapudi/44f8fd1b86f5343306bf985112e2f390 to your computer and use it in GitHub Desktop.
Save vamsitallapudi/44f8fd1b86f5343306bf985112e2f390 to your computer and use it in GitHub Desktop.
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