Created
August 21, 2015 13:54
-
-
Save c4milo/0c51a5bbd90ecad25e69 to your computer and use it in GitHub Desktop.
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 "log" | |
var i int | |
func bsearch(target int, array []int) int { | |
low := 0 | |
hi := len(array) | |
i = 0 | |
for low <= hi { | |
i++ | |
mid := low + (hi-low)/2 | |
if array[mid] == target { | |
return mid | |
} | |
if target > array[mid] { | |
low = mid + 1 | |
} else { | |
hi = mid - 1 | |
} | |
} | |
return -1 | |
} | |
func main() { | |
array := []int{1, 2, 3, 4, 5, 6, 10, 15, 20, 30, 40, 50, 60, 61, 62, 66, 70} | |
target := 5 | |
index := bsearch(target, array) | |
if index != 4 { | |
log.Fatal("Gah, it didn't find it!") | |
} | |
log.Printf("yay! Found in %d iterations", i) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment