diff --git a/binary_search.go b/binary_search.go new file mode 100644 index 0000000000000000000000000000000000000000..d7edb8ce44875839111c108fb40b7cd7150da392 --- /dev/null +++ b/binary_search.go @@ -0,0 +1,70 @@ +package main + +import "fmt" + +// BinarySearch performs binary search on a sorted slice of integers +// Returns the index of the target element, or -1 if not found +func BinarySearch(arr []int, target int) int { + 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 { + right = mid - 1 + } + } + + return -1 +} + +// BinarySearchRecursive performs binary search recursively +func BinarySearchRecursive(arr []int, target, left, right int) int { + if left > right { + return -1 + } + + mid := left + (right-left)/2 + + if arr[mid] == target { + return mid + } else if arr[mid] < target { + return BinarySearchRecursive(arr, target, mid+1, right) + } else { + return BinarySearchRecursive(arr, target, left, mid-1) + } +} + +func main() { + // Test cases + testArray := []int{1, 3, 5, 7, 9, 11, 13, 15, 17, 19} + + fmt.Println("Testing Binary Search:") + fmt.Println("Array:", testArray) + + // Test iterative version + targets := []int{7, 1, 19, 4, 20} + for _, target := range targets { + result := BinarySearch(testArray, target) + if result != -1 { + fmt.Printf("Found %d at index %d\n", target, result) + } else { + fmt.Printf("%d not found in array\n", target) + } + } + + fmt.Println("\nTesting Recursive Binary Search:") + for _, target := range targets { + result := BinarySearchRecursive(testArray, target, 0, len(testArray)-1) + if result != -1 { + fmt.Printf("Found %d at index %d\n", target, result) + } else { + fmt.Printf("%d not found in array\n", target) + } + } +} \ No newline at end of file