Last active
June 1, 2022 06:41
-
-
Save rommansabbir/9d9478eb8e15e7b1ef7c081e5afcba78 to your computer and use it in GitHub Desktop.
BinarySearch
This file contains 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
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