Last active
October 13, 2020 23:10
-
-
Save emre/6340638 to your computer and use it in GitHub Desktop.
binary search implementation on golang slices
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
package main | |
import ( | |
"fmt" | |
) | |
func BinarySearch(target_map []int, value int) int { | |
start_index := 0 | |
end_index := len(target_map) - 1 | |
for start_index <= end_index { | |
median := (start_index + end_index) / 2 | |
if target_map[median] < value { | |
start_index = median + 1 | |
} else { | |
end_index = median - 1 | |
} | |
} | |
if start_index == len(target_map) || target_map[start_index] != value { | |
return -1 | |
} else { | |
return start_index | |
} | |
} | |
func main() { | |
values := []int{1, 2, 3, 4, 5, 6, 7} | |
fmt.Println(BinarySearch(values, 5)) | |
} |
./main.go:19:4: too many arguments to return
I think this is simpler but not sure if it's correct (untested):
start_index := 0 end_index := len(target_map) for start_index < end_index { median := start_index + (end_index - start_index) / 2 if target_map[start_index] == value { return start_index } if target_map[median] < value { start_index = median } else { end_index = median } } return -1
./main.go:19:4: too many arguments to return
func binarySearch(arr []int, val int) int {
first := 0
last := len(arr) - 1
for first <= last {
mid := (first + last) / 2
switch {
case arr[mid] == val:
return mid
case arr[mid] < val:
first = mid + 1
case arr[mid] > val:
last = mid - 1
}
}
return -1
}
You can additionally add validation in case if array of given elements is not sorted for sure
if !sort.IntsAreSorted(target_map) { panic("Given array is not sorted") }
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think this is simpler but not sure if it's correct (untested):