Skip to content

Commit 9087f67

Browse files
authored
Update iterBinarySearch (#245)
* added test for iterBinarySearch and 2 more test cases * Update iterBinarySearch * Updated test failure output to be clearer * Update iterBinarySearch - highIndex should not subtract by 1
1 parent 39eebae commit 9087f67

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

searches/binary_search.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,12 @@ func iterBinarySearch(array []int, target int, lowIndex int, highIndex int) int
1818
startIndex := lowIndex
1919
endIndex := highIndex
2020
var mid int
21-
for startIndex < endIndex {
22-
mid = int(startIndex + (endIndex - startIndex))
21+
for startIndex <= endIndex {
22+
mid = int(startIndex + (endIndex)/2)
2323
if array[mid] > target {
24-
endIndex = mid
24+
endIndex = mid - 1
2525
} else if array[mid] < target {
26-
startIndex = mid
26+
startIndex = mid + 1
2727
} else {
2828
return mid
2929
}

searches/search_test.go

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ type searchTest struct {
1212
var searchTests = []searchTest{
1313
//Sanity
1414
{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5, 4, "Sanity"},
15+
//First
16+
{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 1, 0, "First"},
17+
//Last
18+
{[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 10, 9, "Last"},
1519
//Absent
1620
{[]int{1, 4, 5, 6, 7, 10}, 25, -1, "Absent"},
1721
//Empty slice
@@ -22,7 +26,16 @@ func TestBinarySearch(t *testing.T) {
2226
for _, test := range searchTests {
2327
actual := binarySearch(test.data, test.key, 0, len(test.data)-1)
2428
if actual != test.expected {
25-
t.Errorf("test %s failed", test.name)
29+
t.Errorf("test %s failed: expected '%d', get '%d'", test.name, test.expected, actual)
30+
}
31+
}
32+
}
33+
34+
func TestIterBinarySearch(t *testing.T) {
35+
for _, test := range searchTests {
36+
actual := iterBinarySearch(test.data, test.key, 0, len(test.data)-1)
37+
if actual != test.expected {
38+
t.Errorf("test %s failed: expected '%d', get '%d'", test.name, test.expected, actual)
2639
}
2740
}
2841
}
@@ -31,7 +44,7 @@ func TestLinearSearch(t *testing.T) {
3144
for _, test := range searchTests {
3245
actual := linearSearch(test.data, test.key)
3346
if actual != test.expected {
34-
t.Errorf("test %s failed", test.name)
47+
t.Errorf("test %s failed: expected '%d', get '%d'", test.name, test.expected, actual)
3548
}
3649
}
3750
}

0 commit comments

Comments
 (0)