Binarysearch with Python with recursion - Stack Overflow

def binarysearch(a,n):mid=int(len(a)2) #taking the middle pointif(n==a[mid]): return midelif(n>a[mi

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744881258a4598852.html

相关推荐

  • Binarysearch with Python with recursion - Stack Overflow

    def binarysearch(a,n):mid=int(len(a)2) #taking the middle pointif(n==a[mid]): return midelif(n>a[mi

    1天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信