Skip to content

Instantly share code, notes, and snippets.

@ARACOOOL
Created December 19, 2016 03:34
Show Gist options
  • Save ARACOOOL/4678a14c83f3d1bcc2e74e3fc8d23489 to your computer and use it in GitHub Desktop.
Save ARACOOOL/4678a14c83f3d1bcc2e74e3fc8d23489 to your computer and use it in GitHub Desktop.
In computer science, binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array
package binary
import (
"errors"
"sort"
)
// BinarySearch search binary
func BinarySearch(data []int, searchValue int) (int, error) {
firstIndex := 0
lastIndex := len(data) - 1
if lastIndex == -1 {
return 0, errors.New("Data can not be empty")
}
sort.Ints(data)
if searchValue > data[lastIndex] {
return 0, errors.New("Searching bigger that values in slice")
}
var stepIndex int
for firstIndex <= lastIndex {
stepIndex = (firstIndex + lastIndex) / 2
if data[stepIndex] == searchValue {
return stepIndex, nil
}
if searchValue > data[stepIndex] {
firstIndex = stepIndex + 1
} else {
lastIndex = stepIndex - 1
}
}
return 0, errors.New("Searching value not found")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment