Skip to content

Instantly share code, notes, and snippets.

@mytholog
Created September 11, 2017 09:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mytholog/b3e56567123271e0c91a2a1b05f7df6f to your computer and use it in GitHub Desktop.
Save mytholog/b3e56567123271e0c91a2a1b05f7df6f to your computer and use it in GitHub Desktop.
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