Skip to content

Commit

Permalink
Merge pull request wangzheng0822#96 from scissorsfeet/master
Browse files Browse the repository at this point in the history
 15_binarysearch by golang
  • Loading branch information
wangzheng0822 authored Oct 25, 2018
2 parents 18558ab + 936ccee commit b60926b
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
47 changes: 47 additions & 0 deletions go/15_binarysearch/binarysearch.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package _5_binarysearch

func BinarySearch(a []int, v int) int {
n := len(a)
if n == 0 {
return -1
}

low := 0
high := n - 1
for low <= high {
mid := (low + high) / 2
if a[mid] == v {
return mid
} else if a[mid] > v {
high = mid - 1
} else {
low = mid + 1
}
}

return -1
}

func BinarySearchRecursive(a []int, v int) int {
n := len(a)
if n == 0 {
return -1
}

return bs(a, v, 0, n-1)
}

func bs(a []int, v int, low, high int) int {
if low > high {
return -1
}

mid := (low + high) / 2
if a[mid] == v {
return mid
} else if a[mid] > v {
return bs(a, v, low, mid-1)
} else {
return bs(a, v, mid+1, high)
}
}
27 changes: 27 additions & 0 deletions go/15_binarysearch/binarysearch_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package _5_binarysearch

import "testing"

func TestBinarySearch(t *testing.T) {
var a []int

a = []int{1, 3, 5, 6, 8}
if BinarySearch(a, 8) != 4 {
t.Fatal(BinarySearch(a, 3))
}
if BinarySearch(a, 4) != -1 {
t.Fatal(BinarySearch(a, 4))
}
}

func TestBinarySearchRecursive(t *testing.T) {
var a []int

a = []int{1, 3, 5, 6, 8}
if BinarySearchRecursive(a, 8) != 4 {
t.Fatal(BinarySearch(a, 3))
}
if BinarySearchRecursive(a, 4) != -1 {
t.Fatal(BinarySearch(a, 4))
}
}

0 comments on commit b60926b

Please sign in to comment.