Created
December 19, 2016 03:34
-
-
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
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 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