Skip to content

Instantly share code, notes, and snippets.

@c4milo
Created August 21, 2015 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c4milo/0c51a5bbd90ecad25e69 to your computer and use it in GitHub Desktop.
Save c4milo/0c51a5bbd90ecad25e69 to your computer and use it in GitHub Desktop.
package main
import "log"
var i int
func bsearch(target int, array []int) int {
low := 0
hi := len(array)
i = 0
for low <= hi {
i++
mid := low + (hi-low)/2
if array[mid] == target {
return mid
}
if target > array[mid] {
low = mid + 1
} else {
hi = mid - 1
}
}
return -1
}
func main() {
array := []int{1, 2, 3, 4, 5, 6, 10, 15, 20, 30, 40, 50, 60, 61, 62, 66, 70}
target := 5
index := bsearch(target, array)
if index != 4 {
log.Fatal("Gah, it didn't find it!")
}
log.Printf("yay! Found in %d iterations", i)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment