Skip to content

Instantly share code, notes, and snippets.

@rommansabbir
Last active June 1, 2022 06:41
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 rommansabbir/9d9478eb8e15e7b1ef7c081e5afcba78 to your computer and use it in GitHub Desktop.
Save rommansabbir/9d9478eb8e15e7b1ef7c081e5afcba78 to your computer and use it in GitHub Desktop.
BinarySearch
class BinarySearch {
companion object {
@JvmStatic
fun main(args: Array<String>) {
println("Index position: " + binarySearch(mutableListOf(1,15,34,45,65,76,87), 76))
}
private fun binarySearch(list: List<Int>, itemToFind: Int): Int {
//Starting point
var left = 0
//Ending point
var right = list.size - 1
//Iterate
while (left < right) {
//Find out the middle position
val middle = left + (right - 1) / 2
//Check if the current item is itemToFind, if yes return the index
if (list[middle] == itemToFind) return middle
//If middle index value is less than itemToFind, set left to middle+1
if (list[middle] < itemToFind) {
left = middle + 1
} else {
//Set right to middle -1
right = middle - 1
}
}
return -1
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment