Created
July 13, 2019 02:20
-
-
Save soeirosantos/89d206504fca7a99f245ac4cd4f53d5c to your computer and use it in GitHub Desktop.
Binary Search in Go
This file contains hidden or 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
package search | |
func BinarySearch(arr []int, target int) int { | |
start := 0 | |
end := len(arr) - 1 | |
for start <= end { | |
midPos := (start + end) / 2 | |
if target < arr[midPos] { | |
end = midPos - 1 | |
} else if target > arr[midPos] { | |
start = midPos + 1 | |
} else { | |
return midPos | |
} | |
} | |
return -1 | |
} |
This file contains hidden or 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
package search | |
import ( | |
"testing" | |
) | |
func TestBinarySearch(t *testing.T) { | |
nums := []int{5, 9, 23, 245, 342, 900, 1003, 2000} | |
tables := []struct { | |
target int | |
expected int | |
}{ | |
{5, 0}, | |
{2000, 7}, | |
{342, 4}, | |
{9, 1}, | |
{1000, -1}, | |
} | |
for _, table := range tables { | |
actual := BinarySearch(nums, table.target) | |
if actual != table.expected { | |
t.Errorf("Found is wrong, got: %d, want: %d.", actual, | |
table.expected) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment