Skip to content

Instantly share code, notes, and snippets.

@abdulrahmanAlotaibi
Created February 7, 2023 04:23
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 abdulrahmanAlotaibi/73f5ef2f0c6787949f2508d7d4bd5341 to your computer and use it in GitHub Desktop.
Save abdulrahmanAlotaibi/73f5ef2f0c6787949f2508d7d4bd5341 to your computer and use it in GitHub Desktop.
BinarySearchAlgorithim on sorted array
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello, World!")
arr := []int{1,2,3,4}
fmt.Println(binarySearch(arr, 3))
}
func binarySearch(arr []int , target int) int{
if len(arr) == 0 {
return -1
}
left := 0
right := len(arr)-1
for left <= right {
mid := left + (right - left) / 2
if arr[mid] == target {
return mid
} else if arr[mid] < target {
left = mid + 1
} else {
left = mid - 1
}
}
return -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment