Created
September 11, 2017 09:46
-
-
Save mytholog/b3e56567123271e0c91a2a1b05f7df6f to your computer and use it in GitHub Desktop.
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
func binarySearch(a []int, search int) (result int, searchCount int) { | |
mid := len(a) / 2 | |
switch { | |
case len(a) == 0: | |
result = -1 // not found | |
case a[mid] > search: | |
result, searchCount = binarySearch(a[:mid], search) | |
case a[mid] < search: | |
result, searchCount = binarySearch(a[mid+1:], search) | |
result += mid + 1 | |
default: // a[mid] == search | |
result = mid // found | |
} | |
searchCount++ | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment