Skip to content

Instantly share code, notes, and snippets.

@soeirosantos
Created July 13, 2019 02:20
Show Gist options
  • Save soeirosantos/89d206504fca7a99f245ac4cd4f53d5c to your computer and use it in GitHub Desktop.
Save soeirosantos/89d206504fca7a99f245ac4cd4f53d5c to your computer and use it in GitHub Desktop.
Binary Search in Go
package search
func BinarySearch(arr []int, target int) int {
start := 0
end := len(arr) - 1
for start <= end {
midPos := (start + end) / 2
if target < arr[midPos] {
end = midPos - 1
} else if target > arr[midPos] {
start = midPos + 1
} else {
return midPos
}
}
return -1
}
package search
import (
"testing"
)
func TestBinarySearch(t *testing.T) {
nums := []int{5, 9, 23, 245, 342, 900, 1003, 2000}
tables := []struct {
target int
expected int
}{
{5, 0},
{2000, 7},
{342, 4},
{9, 1},
{1000, -1},
}
for _, table := range tables {
actual := BinarySearch(nums, table.target)
if actual != table.expected {
t.Errorf("Found is wrong, got: %d, want: %d.", actual,
table.expected)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment