Skip to content

Instantly share code, notes, and snippets.

@Sunpacker
Forked from echohes/bin_search.go
Created January 18, 2024 13:59
Show Gist options
  • Select an option

  • Save Sunpacker/d7cc2c947f05e925a345f1cf95e3c635 to your computer and use it in GitHub Desktop.

Select an option

Save Sunpacker/d7cc2c947f05e925a345f1cf95e3c635 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