Last active
September 18, 2022 18:14
-
-
Save maxclav/1fc17056fcc9df9ad485cac8f1e7fbb8 to your computer and use it in GitHub Desktop.
Simple binary search on a slice (array) in Go (GoLang).
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
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