Last active
May 13, 2023 13:25
-
-
Save rnemeth90/cb5a95eb0166f81ae9a47fb801945628 to your computer and use it in GitHub Desktop.
Go Binary Search
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 main | |
import ( | |
"fmt" | |
"math" | |
) | |
func main() { | |
fmt.Println("index", binarySearch([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 8)) | |
} | |
func binarySearch(intSlice []int, value int) int { | |
lowerBound := 0 | |
upperBound := len(intSlice) - 1 | |
for lowerBound <= upperBound { | |
midIndex := math.Floor(float64((lowerBound + upperBound) / 2)) | |
valueAtMid := intSlice[int(midIndex)] | |
if value == valueAtMid { | |
return int(midIndex) | |
} else if value < valueAtMid { | |
upperBound = int(midIndex) - 1 | |
} else if value > valueAtMid { | |
lowerBound = int(midIndex) + 1 | |
} | |
} | |
return -1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment