From 8efbbb8b542430203c45e596941b76608bfedbe6 Mon Sep 17 00:00:00 2001 From: dior Date: Thu, 26 Dec 2024 15:42:36 +0500 Subject: [PATCH] fix examples: make them same as in the book; make code cleaner; add comments --- .../Golang/BinarySearch.go | 44 ++++++++++++------- 1 file changed, 28 insertions(+), 16 deletions(-) diff --git a/01_introduction_to_algorithms/Golang/BinarySearch.go b/01_introduction_to_algorithms/Golang/BinarySearch.go index d360d1aa..e5e74d27 100644 --- a/01_introduction_to_algorithms/Golang/BinarySearch.go +++ b/01_introduction_to_algorithms/Golang/BinarySearch.go @@ -2,43 +2,55 @@ package main import "fmt" -func checkBin(list []int, i int) int { +func checkBin(list []int, i int) interface{} { + // low and high keep track of which part of the list you'll search in. low := 0 high := len(list) - 1 + // While you haven't narrowed it down to one element ... for low <= high { + // ... check the middle element mid := (low + high) / 2 + // Found the item. if list[mid] == i { return mid } - if list[mid] < i { - low = mid + 1 - } else { + // The guess was too high. + if list[mid] > i { high = mid - 1 + // The guess was too low. + } else { + low = mid + 1 } } - return -1 + // Item doesn't exist + return nil } -func RecursiveCheckBin(list []int, item int, high, low int) int { +func recursiveCheckBin(list []int, item int, high, low int) interface{} { + // Check base case if high >= low { mid := (high + low) / 2 - + // If element is present at the middle itself if list[mid] == item { return mid + // If element is smaller than mid, then it can only + // be present in left subarray } else if list[mid] > item { - return RecursiveCheckBin(list, item, mid-1, low) + return recursiveCheckBin(list, item, mid - 1, low) + // Else the element can only be present in right subarray } else { - return RecursiveCheckBin(list, item, high, mid+1) + return recursiveCheckBin(list, item, high, mid + 1) } } - return -1 + // Element is not present in the array + return nil } - +// you can run this code on: https://go.dev/play/ 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 + list := []int{1, 3, 5, 7, 9} + fmt.Println(checkBin(list, 3)) // => 1 + fmt.Println(checkBin(list, -1)) // => + fmt.Println(recursiveCheckBin(list, 3, len(list)-1, 0)) // => 1 + fmt.Println(recursiveCheckBin(list, -1, len(list)-1, 0)) // => }