Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Search in Go - why the heck is this incorrect

Cant figure out why the heck is this incorrect implementation of Binary Search in go. Input is ([]int{-1, 0, 3, 5, 9, 12}, 9)

func Search(nums []int, target int) int {

    mid := len(nums) / 2

    if nums[mid] == target {
        return mid
    }
    if len(nums) >= 1 {
        if nums[mid] < target {
            return Search(nums[mid+1:], target)
        } else {
            return Search(nums[:mid], target)
        }
    }

    return -1
}
like image 242
lily Avatar asked Oct 15 '25 15:10

lily


1 Answers

Binary Search

Updated to fix infinite recursion

Thanks @sprutex for finding the bug

func Search(nums []int, target int) int {
    mid := len(nums) / 2

    if nums[mid] == target {
        return mid
    }
    if len(nums) > 1 {
        if nums[mid] < target {
            res := Search(nums[mid:], target)
            if res == -1 {
                return -1
            }
            return res + mid
        } else {
            return Search(nums[:mid], target)
        }
    }

    return -1
}

Original answer

DO NOT USE - contains infinite recursion bug when searching for an item not in the list.

func Search(nums []int, target int) int {

    mid := len(nums) / 2

    if nums[mid] == target {
        return mid
    }
    if len(nums) >= 1 {
        if nums[mid] < target {
            return Search(nums[mid:], target) + mid
        } else {
            return Search(nums[:mid], target)
        }
    }

    return -1
}

The one line that was changed is the following:

return Search(nums[mid:], target) + mid

like image 165
SargeATM Avatar answered Oct 17 '25 11:10

SargeATM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!