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 -

  1. 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.

  2. your print statement after break, should put before break, otherwise not executed.

  3. your recalculation of middle inside else block, need recalculate middle case of array[middle] < search well, better solution put recalculation outside else block, directly inside while 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

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -