Skip to content

Commit 0b38cd4

Browse files
Merge pull request #258 from zhangmingkai4315/fix-binary-search
fix stack overflow problem and add more test
2 parents 20aa579 + dcecf5b commit 0b38cd4

File tree

2 files changed

+25
-7
lines changed

2 files changed

+25
-7
lines changed

searches/binarysearch.go

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
package searches
22

3+
34
func binarySearch(array []int, target int, lowIndex int, highIndex int) int {
4-
if highIndex < lowIndex {
5+
if highIndex < lowIndex || len(array) == 0{
56
return -1
67
}
7-
mid := int(lowIndex + (highIndex-lowIndex)/2)
8+
mid := (highIndex+lowIndex)/2
89
if array[mid] > target {
9-
return binarySearch(array, target, lowIndex, mid)
10+
return binarySearch(array, target, lowIndex, mid-1)
1011
} else if array[mid] < target {
1112
return binarySearch(array, target, mid+1, highIndex)
1213
} else {
@@ -18,12 +19,16 @@ func iterBinarySearch(array []int, target int, lowIndex int, highIndex int) int
1819
startIndex := lowIndex
1920
endIndex := highIndex
2021
var mid int
21-
for startIndex < endIndex {
22-
mid = int(startIndex + (endIndex - startIndex))
22+
size := len(array)
23+
if size ==0 || highIndex > size || lowIndex < 0 {
24+
return -1
25+
}
26+
for startIndex <= endIndex {
27+
mid = (endIndex + startIndex)/2
2328
if array[mid] > target {
24-
endIndex = mid
29+
endIndex = mid-1
2530
} else if array[mid] < target {
26-
startIndex = mid
31+
startIndex = mid+1
2732
} else {
2833
return mid
2934
}

searches/search_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,11 @@ type searchTest struct {
1111

1212
var searchTests = []searchTest{
1313
//Sanity
14+
{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 1, 0, "Sanity"},
1415
{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5, 4, "Sanity"},
16+
{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 10, 9, "Sanity"},
1517
//Absent
18+
{[]int{1, 4, 5, 6, 7, 10}, -25, -1, "Absent"},
1619
{[]int{1, 4, 5, 6, 7, 10}, 25, -1, "Absent"},
1720
//Empty slice
1821
{[]int{}, 2, -1, "Empty"},
@@ -27,6 +30,15 @@ func TestBinarySearch(t *testing.T) {
2730
}
2831
}
2932

33+
func TestIterBinarySearch(t *testing.T) {
34+
for _, test := range searchTests {
35+
actual := iterBinarySearch(test.data, test.key, 0, len(test.data)-1)
36+
if actual != test.expected {
37+
t.Errorf("test %s failed", test.name)
38+
}
39+
}
40+
}
41+
3042
func TestLinearSearch(t *testing.T) {
3143
for _, test := range searchTests {
3244
actual := linearSearch(test.data, test.key)
@@ -35,3 +47,4 @@ func TestLinearSearch(t *testing.T) {
3547
}
3648
}
3749
}
50+

0 commit comments

Comments
 (0)