Last active
September 7, 2022 08:49
-
-
Save mohamedallam1991/53ed09e20ec19bcb3aa4e036c3f35d3a to your computer and use it in GitHub Desktop.
Binary Search in Golang and Linear Search method
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 main() { | |
b := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 100, 159, 192, 350, 1230, 1341, 4533} | |
fmt.Println(BinarySearch(b, 31)) | |
fmt.Println(LinearSearch(b, 31)) | |
} | |
func BinarySearch(haystack []int, needle int) bool { | |
var high, low, mid, val int | |
low = 0 | |
high = len(haystack) | |
for low < high { | |
mid = (low + ((high - low) / 2)) | |
val = haystack[mid] | |
fmt.Println(val) | |
if val == needle { | |
return true | |
} else if val > needle { | |
high = mid | |
} else if val < needle { | |
low = mid + 1 | |
} | |
} | |
return false | |
} | |
func LinearSearch(haystack []int, needle int) bool { | |
for _, v := range haystack { | |
fmt.Println(v) | |
if v == needle { | |
return true | |
} | |
} | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment