Created
February 7, 2023 04:23
-
-
Save abdulrahmanAlotaibi/73f5ef2f0c6787949f2508d7d4bd5341 to your computer and use it in GitHub Desktop.
BinarySearchAlgorithim on sorted array
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() { | |
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