Created
February 13, 2022 22:45
-
-
Save echohes/e66d56ae01370bc57fde65e52dee7cea to your computer and use it in GitHub Desktop.
binary search in Golang
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 binary_search(arr []int, item int) int { | |
max := len(arr) | |
low := 0 | |
for low <= max { | |
mid := (low + max) / 2 | |
fmt.Println(low, max, mid) | |
if arr[mid] == item { | |
return mid | |
} | |
if arr[mid] > item { | |
max = mid - 1 | |
} else { | |
low = mid + 1 | |
} | |
} | |
return 0 | |
} | |
func main() { | |
//create test array | |
min, max := 1, 100000 | |
x := make([]int, max) | |
for i := range x { | |
x[i] = i + min | |
} | |
fmt.Println(binary_search(x, 1)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment