Skip to content

Instantly share code, notes, and snippets.

@rnemeth90
Last active May 13, 2023 13:25
Show Gist options
  • Save rnemeth90/cb5a95eb0166f81ae9a47fb801945628 to your computer and use it in GitHub Desktop.
Save rnemeth90/cb5a95eb0166f81ae9a47fb801945628 to your computer and use it in GitHub Desktop.
Go Binary Search
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println("index", binarySearch([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 8))
}
func binarySearch(intSlice []int, value int) int {
lowerBound := 0
upperBound := len(intSlice) - 1
for lowerBound <= upperBound {
midIndex := math.Floor(float64((lowerBound + upperBound) / 2))
valueAtMid := intSlice[int(midIndex)]
if value == valueAtMid {
return int(midIndex)
} else if value < valueAtMid {
upperBound = int(midIndex) - 1
} else if value > valueAtMid {
lowerBound = int(midIndex) + 1
}
}
return -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment