python - Why my logic is not working for Binary search program? -
i'm trying create binary search
program using python. every time stuck while loop
. looks need put break
every condition. it'd create mess whole logic.
kindly me, how rid of such situations:
print("enter number of elements:") num = int(input()) array = [] print("enter %d elements" %num) c in range(0, num): arraynum = int(input()) #use "append" concept under array python. array.append(arraynum) print("enter value want find: ") search = int(input()) first = int(0) last = int(num-1) middle = int((first + last)/2) while first <= last: if array[middle] < search: first = int(middle+1) elif array[middle] == search: break print("%d found @ location" % search, (middle+1)) else: last = int(middle-1) middle = int((first+last)/2) if first > last: print("%d not present in list"%search)
when run program, looks while loop
still running. please me.
help appreciated!
three potential issues -
binary search works on sorted lists, may not entering sorted list . make sure list sorted before starting binary search -
array.sort()
do before starting binary search while loop.
your print statement after break, should put before break, otherwise not executed.
your recalculation of
middle
insideelse
block, need recalculate middle case ofarray[middle] < search
well, better solution put recalculation outside else block, directly insidewhile
block.
example -
while first <= last: if array[middle] < search: first = int(middle+1) elif array[middle] == search: print("%d found @ location" % search, (middle+1)) break else: last = int(middle-1) middle = int((first+last)/2)
Comments
Post a Comment