Skip to content

Instantly share code, notes, and snippets.

@derekkenney
Last active July 5, 2019 16:57
Show Gist options
  • Save derekkenney/bcd6a20d611dd4ea39ac7476fc4eba4d to your computer and use it in GitHub Desktop.
Save derekkenney/bcd6a20d611dd4ea39ac7476fc4eba4d to your computer and use it in GitHub Desktop.
An example of implementing binary search in Go

Binary Search implementation in Go

  • $ go run main.go Returns a bool if the search value was found or not
// Find elements within a list by conistently reducing the
// amount of data to be searched
package main
import (
"log"
"sort"
"sync"
)
// median is the middle index of the slice
// high is the upper bound, len(arr) -1
// low is the lower bound, 0
func main() {
n1 := 2
n2 := 10
s1 := []int{1, 2, 3, 9, 4, 11, 7, 20}
s2 := []int{10, 12, 13, 9, 4, 11, 7, 21}
wg := new(sync.WaitGroup)
go binarySearch(n1, s1, wg)
go binarySearch(n2, s2, wg)
wg.Add(2)
wg.Wait()
}
// Search slice for the value of n
func binarySearch(n int, s []int, wg *sync.WaitGroup) {
low := 0
high := len(s) - 1
// If low <= high, search for n
sort.Ints(s)
for low <= high {
median := (low + high) / 2
// If n is less than median, search lower
if s[median] < n {
low = median + 1
} else {
high = median - 1
}
}
// n wasn't found in slice
if low == len(s) || s[low] != n {
log.Printf("Didn't find %v", n)
} else {
log.Printf("Found %v", n)
}
wg.Done()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment