Merge pull request #96 from scissorsfeet/master
15_binarysearch by golang
This commit is contained in:
commit
b60926b526
47
go/15_binarysearch/binarysearch.go
Normal file
47
go/15_binarysearch/binarysearch.go
Normal 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)
|
||||
}
|
||||
}
|
27
go/15_binarysearch/binarysearch_test.go
Normal file
27
go/15_binarysearch/binarysearch_test.go
Normal 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))
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user