Skip to content

Commit aa5342c

Browse files
committed
feat: binary search
1 parent ed7b9a2 commit aa5342c

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

go/pkg/array/search.go

+19-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,23 @@
11
package array
22

3-
func binarySearch(arr []int) {
3+
func BinarySearch(arr []int, item int) int {
4+
low := 0
5+
high := len(arr) - 1
46

7+
for high >= low {
8+
guess := (high + low) / 2
9+
10+
if guess == item {
11+
return guess
12+
}
13+
14+
if guess > item {
15+
high = guess - 1
16+
} else {
17+
low = guess + 1
18+
}
19+
20+
}
21+
22+
return 0
523
}

go/pkg/array/search_test.go

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package array_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/vitorsavian/algo/pkg/array"
7+
)
8+
9+
func TestBinarySearch(t *testing.T) {
10+
arr := make([]int, 100)
11+
12+
want := 27
13+
14+
n := 1
15+
for n <= 100 {
16+
arr[n-1] = n
17+
n++
18+
}
19+
20+
result := array.BinarySearch(arr, want)
21+
22+
if want != result {
23+
t.Fatalf("Unable to get binary search right: %d", result)
24+
}
25+
}

go/pkg/array/sort.go

+5
Original file line numberDiff line numberDiff line change
@@ -1 +1,6 @@
11
package array
2+
3+
func InsertSort(arr []int) []int {
4+
var stuff []int
5+
return stuff
6+
}

0 commit comments

Comments
 (0)