diff --git a/slice_searching/binary_search/binary_search.go b/slice_searching/binary_search/binary_search.go new file mode 100644 index 0000000..d3a943f --- /dev/null +++ b/slice_searching/binary_search/binary_search.go @@ -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 + } + } + +} diff --git a/slice_searching/binary_search/binary_search_test.go b/slice_searching/binary_search/binary_search_test.go new file mode 100644 index 0000000..444f0eb --- /dev/null +++ b/slice_searching/binary_search/binary_search_test.go @@ -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) + } + }) + } +}