0
def binarySearch(nums,low,high,target):

    if low<=high:
        mid=(low+high)//2

        if nums[mid]==target:
            return mid
        if nums[mid]<target:
            binarySearch(nums,mid+1,high,target)
        else:
            binarySearch(nums,low,mid-1,target)
    else:
        return -1

def search(nums, target):
    return binarySearch(nums,0,len(nums)-1,target)
    

nums=[-1,0,3,5,9,12]
target=9

print(search(nums,target))

console output

Expected output of the above python code for binary search is '4'. But my output is 'None'. I also printed the value of mid on console output just before the line "return mid"(line number 7), it was showing the expected value '4'. But it returns 'None' instead of that expected value. Please find out the problem and it's solution.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • Welcome to Stack Overflow. Your 'else' condition returns a value. Your ```if``` condition branch doesn't. – ewokx Jul 29 '22 at 06:15
  • Try adding `return` to your `binarySearch(nums,mid+1,high,target)` lines. – 101 Jul 29 '22 at 06:16
  • You *aren't* returning an explicit value when you make a recursive call; you're ignoring the recursive call's return value and implicitly returning `None`. – chepner Jul 29 '22 at 21:12

1 Answers1

-1
  if nums[mid]<target:
            return binarySearch(nums,mid+1,high,target)
        else:
            return binarySearch(nums,low,mid-1,target)
pythonHua
  • 61
  • 6