sorting - anything wrong with below binary search code in Python -


let function perspective. thanks.

def binarysearch(array, beginindex, endindex, value):     while (beginindex < endindex):         mid = (beginindex + endindex) // 2         if array[mid] < value:             beginindex = mid + 1         elif array[mid] > value:             endindex = mid - 1         else: #equal             return mid      if array[beginindex] == value:         return beginindex     else:         return -1 

here cases tested,

print binarysearch([2,3], 0, 1, 2) print binarysearch([2,3], 0, 1, 3) print binarysearch([2,3], 0, 1, -1) print binarysearch([2,3,3,3,4,5], 0, 5, 3) 

thanks in advance, lin

well, first thing "wrong" (if production code rather class assignment or personal exercise) you're reinventing wheel. python provides binary search part of included batteries through bisect module (and yes, it's on python 2 well).

beyond that, doesn't work cases. example, tried:

binarysearch(list(range(1000)), 0, 1000, 6) # , again 999 in case end index inclusive 

and got no hit. because loop never loops; presumably need dedent final if/else it's not part of while loop, because is, never make more 1 (and half, counting if/else) set of tests in before succeeding or giving up.

fixing indent issue (and if you're on python 3 or using __future__ division import on python 2, changing / 2 // 2) makes work, , seems standard implementation of algorithm.

a couple suggestions:

  1. python tends use half-open ranges; accept beginindex , endindex inclusive values, typically python functions accept start , end, start inclusive, , end exclusive (the way range behaves).
  2. moving beginindex/endindex` arguments end of profile allow give them useful defaults, in common case (searching whole sequence), users wouldn't have manually specify bounds. example:

    def binarysearch(array, value, beginindex=0, endindex=none): if endindex none: endindex = len(array) - 1 # or len(array) if rewrite half-open ...

would make simpler call in standard case (and not coincidentally, that's profile used bisect.bisect).

on fixing indent issue (per request in comments), i'm saying following 4 lines (which indented level of while loop's body), should dedented level, they're run when while loop exits without return-ing, instead of every execution of while loop (which, since there return on either path, means while loop never loops):

if array[beginindex] == value:     return beginindex else:     return -1 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -