Skip to content

Commit

Permalink
Binary Search
Browse files Browse the repository at this point in the history
  • Loading branch information
ale8k committed Dec 7, 2021
1 parent 131942c commit 9100bf2
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
21 changes: 21 additions & 0 deletions slice_searching/binary_search/binary_search.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package binarysearch

// Runs a binary search on a given slice numerical values
func BinarySearch(param int, slice []int) int {
low := 0
high := len(slice) - 1
mid := low + (high-low)/2

for {
if mid > len(slice)-1 || mid < 0 {
return -1
} else if slice[mid] > param {
mid -= 1
} else if slice[mid] < param {
mid += 1
} else {
return mid
}
}

}
47 changes: 47 additions & 0 deletions slice_searching/binary_search/binary_search_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package binarysearch

import "testing"

func TestBinarySearch(t *testing.T) {
type args struct {
param int
slice []int
}
tests := []struct {
name string
args args
want int
}{
{
name: "it correctly finds the expected index",
args: args{
param: 4,
slice: []int{6, 8, 2, 4, 6},
},
want: 3,
},
{
name: "it returns -1 when out of bounds > length",
args: args{
param: 10,
slice: []int{6, 8, 2, 4, 6},
},
want: -1,
},
{
name: "it returns -1 when mid < 0",
args: args{
param: -1,
slice: []int{6, 8, 2, 4, 6},
},
want: -1,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := BinarySearch(tt.args.param, tt.args.slice); got != tt.want {
t.Errorf("BinarySearch() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 9100bf2

Please sign in to comment.