Skip to content

Instantly share code, notes, and snippets.

@xissy
Last active October 15, 2017 07:42
Show Gist options
  • Save xissy/1f275ad84fbd495175d2dbb162943129 to your computer and use it in GitHub Desktop.
Save xissy/1f275ad84fbd495175d2dbb162943129 to your computer and use it in GitHub Desktop.
Binary search in Go
package binarysearch
import (
"errors"
)
func BinarySearch(a []int, target int) (int, error) {
startPos := 0
endPos := len(a)
for true {
if startPos == endPos {
return -1, errors.New("no target in the array")
}
mid := (endPos + startPos) / 2
c := a[mid]
if target == c {
return mid, nil
} else if target < c {
endPos = mid
continue
} else {
startPos = mid + 1
continue
}
}
return 0, nil
}
package binarysearch
import (
"errors"
"testing"
)
func TestBinarySearch1(t *testing.T) {
a := []int{1, 2, 3, 4, 5}
for i, v := range a {
r, err := BinarySearch(a, v)
if err != nil {
t.Error(err)
}
if r != i {
t.Error(errors.New("wrong"))
}
}
}
func TestBinarySearch2(t *testing.T) {
a := []int{1, 2, 3, 4, 5}
_, err := BinarySearch(a, 0)
if err != nil {
t.Log(err)
} else {
t.Error(errors.New("wrong"))
}
}
func TestBinarySearch3(t *testing.T) {
a := []int{1, 2, 3, 4, 5}
_, err := BinarySearch(a, 6)
if err != nil {
t.Log(err)
} else {
t.Error(errors.New("wrong"))
}
}
func TestBinarySearch4(t *testing.T) {
a := []int{1, 2, 3, 4, 5, 6}
for i, v := range a {
r, err := BinarySearch(a, v)
if err != nil {
t.Error(err)
}
if r != i {
t.Error(errors.New("wrong"))
}
}
}
func TestBinarySearch5(t *testing.T) {
a := []int{1}
for i, v := range a {
r, err := BinarySearch(a, v)
if err != nil {
t.Error(err)
}
if r != i {
t.Error(errors.New("wrong"))
}
}
}
func TestBinarySearch6(t *testing.T) {
a := []int{}
for i, v := range a {
r, err := BinarySearch(a, v)
if err != nil {
t.Error(err)
}
if r != i {
t.Error(errors.New("wrong"))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment