From c8ff601c527789a76a5ba6b4979f9e06960013e5 Mon Sep 17 00:00:00 2001 From: Armin Date: Sat, 7 Dec 2024 17:09:40 +0330 Subject: [PATCH] feat: enhance recursive binary search to correctly return found index (#298) Co-authored-by: armin --- .../Golang/BinarySearch.go | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/01_introduction_to_algorithms/Golang/BinarySearch.go b/01_introduction_to_algorithms/Golang/BinarySearch.go index 988f541..d360d1a 100644 --- a/01_introduction_to_algorithms/Golang/BinarySearch.go +++ b/01_introduction_to_algorithms/Golang/BinarySearch.go @@ -19,7 +19,26 @@ func checkBin(list []int, i int) int { return -1 } -func main() { - fmt.Println(checkBin([]int{1, 2, 3, 4, 5}, 1)) // 0 - fmt.Println(checkBin([]int{1, 2, 3, 4, 5}, -1)) // -1 +func RecursiveCheckBin(list []int, item int, high, low int) int { + if high >= low { + mid := (high + low) / 2 + + if list[mid] == item { + return mid + } else if list[mid] > item { + return RecursiveCheckBin(list, item, mid-1, low) + } else { + return RecursiveCheckBin(list, item, high, mid+1) + } + + } + return -1 +} + +func main() { + list := []int{1, 2, 3, 4, 5} + fmt.Println(checkBin(list, 2)) // 0 + fmt.Println(checkBin(list, -1)) // -1 + fmt.Println(RecursiveCheckBin([]int{1, 2, 3, 4, 5}, 2, len(list)-1, 0)) // 1 + fmt.Println(RecursiveCheckBin([]int{1, 2, 3, 4, 5}, 0, len(list)-1, 0)) //-1 }