Created
May 10, 2021 21:09
-
-
Save kiambogo/eb2e45763b7cdde2a99056e6ca82da81 to your computer and use it in GitHub Desktop.
Go Binary Search
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" | |
) | |
func main() { | |
assert(false, binarySearch([]int{}, 5)) | |
assert(false, binarySearch([]int{4}, 5)) | |
assert(true, binarySearch([]int{5}, 5)) | |
assert(true, binarySearch([]int{1, 2, 3, 4, 5}, 5)) | |
assert(true, binarySearch([]int{1, 2, 3, 4, 5}, 1)) | |
assert(true, binarySearch([]int{1, 2, 3, 4, 5}, 3)) | |
assert(true, binarySearch([]int{1, 2, 3, 4, 5, 6, 7, 8, 9}, 8)) | |
assert(false, binarySearch([]int{1, 2, 3, 4, 5, 6, 7, 8, 9}, 10)) | |
} | |
func binarySearch(arr []int, n int) bool { | |
if len(arr) == 0 { | |
return false | |
} | |
midIndex := len(arr) / 2 | |
if arr[midIndex] == n { | |
return true | |
} | |
if arr[midIndex] < n { | |
return binarySearch(arr[midIndex+1:], n) | |
} | |
return binarySearch(arr[:midIndex], n) | |
} | |
func assert(expected, actual interface{}) { | |
if expected != actual { | |
log.Panicf("%s != %s", expected, actual) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment