Skip to content

Instantly share code, notes, and snippets.

@maxclav
Last active September 18, 2022 18:14
Show Gist options
  • Save maxclav/1fc17056fcc9df9ad485cac8f1e7fbb8 to your computer and use it in GitHub Desktop.
Save maxclav/1fc17056fcc9df9ad485cac8f1e7fbb8 to your computer and use it in GitHub Desktop.
Simple binary search on a slice (array) in Go (GoLang).
package slice
// BinarySearch searches a `target` value in `nums`
// using the "binary search" algorithm.
// It returns its position if found or -1 if not found.
func BinarySearch(nums []int, target int) int {
if len(nums) == 0 {
return -1
}
for left, right := 0, len(nums)-1; left <= right; {
pos := left + (right - left) / 2
val := nums[pos]
if val == target {
return pos
} else if val < target {
left = pos + 1
} else /* if val > target */ {
right = pos - 1
}
}
return -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment