Example Binary search in Javascript and Go
function BinarySearch(array, number) {
var minIndex = 0
var maxIndex = array.length - 1
while (minIndex <= maxIndex) {
var midIndex = Math.floor((maxIndex + minIndex) / 2)
var midItem = array[midIndex]
if (number == midItem) {
minIndex = maxIndex + 1
return midIndex
}
if (midItem < number) {
minIndex = midIndex + 1
} else if (midItem > number) {
maxIndex = midIndex - 1
}
}
return -1
}
func BinarySearch(array []int, number int) int {
minIndex := 0
maxIndex := len(array) - 1
for minIndex <= maxIndex {
midIndex := int((maxIndex + minIndex) / 2)
midItem := array[midIndex]
if number == midItem {
return midIndex
}
if midItem < number {
minIndex = midIndex + 1
} else if midItem > number {
maxIndex = midIndex - 1
}
}
return -1
}