最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Binarysearch with Python with recursion - Stack Overflow

programmeradmin1浏览0评论
def binarysearch(a,n):
  mid=int(len(a)/2) #taking the middle point
  if(n==a[mid]): 
   return mid
  elif(n>a[mid]): #if greater then do binarysearch in smaller part
   binarysearch(a[(mid+1):],n)
  elif(n<a[mid]):
   binarysearch(a[0:mid],n)

Hello this is my code and my test case is binarysearch([0,2,4,5],2) and it is returning none but I think it should return 1.Because it goes to elif(n<a[mid]) part in that case and return mid if you gave me minus because of not explaining correct it now `

def binarysearch(a,n):
  mid=int(len(a)/2) #taking the middle point
  if(n==a[mid]): 
   return mid
  elif(n>a[mid]): #if greater then do binarysearch in smaller part
   binarysearch(a[(mid+1):],n)
  elif(n<a[mid]):
   binarysearch(a[0:mid],n)

Hello this is my code and my test case is binarysearch([0,2,4,5],2) and it is returning none but I think it should return 1.Because it goes to elif(n<a[mid]) part in that case and return mid if you gave me minus because of not explaining correct it now `

Share edited Mar 9 at 1:29 maths and chess asked Mar 9 at 1:07 maths and chessmaths and chess 1074 bronze badges 3
  • If you're doing binary search in python it's worth learning about standard library module bisect – Stef Commented Mar 10 at 10:20
  • 1 This question is similar to: Why does my recursive function return None?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – EuanG Commented Mar 11 at 13:52
  • Your code has a small issue, it doesn't return the result of the recursive calls. When the function makes a recursive call, it doesn't return the index found in that recursive search. – Christian Will Commented Mar 12 at 23:17
Add a comment  | 

2 Answers 2

Reset to default 1

Besides the bugs (not having return for the recursive call, not taking into account the offset of the slice), this is not how binary search is supposed to work:

Slicing is killing the performance benefit you would get from binary search. While the standard binary search search algorithm has a O(log

发布评论

评论列表(0)

  1. 暂无评论