Created
February 5, 2024 22:31
-
-
Save harryhanYuhao/bfe4ba604d5fbb5d38ca7f1372983463 to your computer and use it in GitHub Desktop.
binary search in go
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
// Expected input: a sorted array | |
// Return: index n, such that array[n] <= target < array[n+1] | |
func binarySearch(array []uint64, target uint64) (int, error) { | |
var lower, upper = 0, len(array) - 1 | |
var preLower, preUpper = 0, len(array) - 1 | |
for array[lower] > target || array[lower+1] <= target { | |
if array[lower+1] == target { | |
return lower + 1, nil | |
} | |
midpoint := (lower + upper) / 2 | |
if array[midpoint] < target { | |
lower = midpoint | |
} else { | |
upper = midpoint | |
} | |
// Error handling | |
if lower == preLower && upper == preUpper { | |
return lower, errors.New("Unable to find target") | |
} | |
preLower = lower | |
preUpper = upper | |
} | |
return lower, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment