forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request wangzheng0822#96 from scissorsfeet/master
15_binarysearch by golang
- Loading branch information
Showing
2 changed files
with
74 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | ||
} | ||
} |