Skip to content

Instantly share code, notes, and snippets.

@mohamedallam1991
Last active September 7, 2022 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohamedallam1991/53ed09e20ec19bcb3aa4e036c3f35d3a to your computer and use it in GitHub Desktop.
Save mohamedallam1991/53ed09e20ec19bcb3aa4e036c3f35d3a to your computer and use it in GitHub Desktop.
Binary Search in Golang and Linear Search method
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