Merge pull request #96 from scissorsfeet/master

15_binarysearch by golang
This commit is contained in:
wangzheng0822 2018-10-25 17:29:49 +08:00 committed by GitHub
commit b60926b526
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 74 additions and 0 deletions

View File

@ -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)
}
}

View File

@ -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))
}
}