-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
ale8k
committed
Dec 7, 2021
1 parent
131942c
commit 9100bf2
Showing
2 changed files
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
}) | ||
} | ||
} |