Skip to content

Instantly share code, notes, and snippets.

@echohes
Created February 13, 2022 22:45
Show Gist options
  • Save echohes/e66d56ae01370bc57fde65e52dee7cea to your computer and use it in GitHub Desktop.
Save echohes/e66d56ae01370bc57fde65e52dee7cea to your computer and use it in GitHub Desktop.
binary search in Golang
package main
import (
"fmt"
)
func binary_search(arr []int, item int) int {
max := len(arr)
low := 0
for low <= max {
mid := (low + max) / 2
fmt.Println(low, max, mid)
if arr[mid] == item {
return mid
}
if arr[mid] > item {
max = mid - 1
} else {
low = mid + 1
}
}
return 0
}
func main() {
//create test array
min, max := 1, 100000
x := make([]int, max)
for i := range x {
x[i] = i + min
}
fmt.Println(binary_search(x, 1))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment