Reputation: 3
I'm trying to create my Binary Search
program using Python. But every time i get stuck with while loop
. It looks i need to put break
for every condition. But it'd would create a mess for my whole logic.
Kindly help me, How to get rid of such situations:
print("Enter your number of elements:")
num = int(input())
array = []
print("Enter your %d elements" %num)
for c in range(0, num):
arrayNum = int(input())
#Use "append" concept under array into python.
array.append(arrayNum)
print("Enter a value which you want to 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 is found at location" % search, (middle+1))
else:
last = int(middle-1)
middle = int((first+last)/2)
if first > last:
print("%d is not present in list"%search)
When i run my program, It looks while loop
is still running. Please help me.
HELP WOULD BE APPRECIATED!
Upvotes: 0
Views: 55
Reputation: 90899
Three potential issues -
Binary search only works on sorted lists, you may not be entering sorted list . To make sure that the list is sorted before starting binary search do -
array.sort()
Do this before starting binary search while loop.
Your print statement is after the break, you should put it before break, otherwise it will not get executed.
Your recalculation of middle
is inside the else
block, but you need to recalculate middle for the case of array[middle] < search
as well, a better solution would be to put that recalculation outside the else block, directly inside the while
block.
Example -
while first <= last:
if array[middle] < search:
first = int(middle+1)
elif array[middle] == search:
print("%d is found at location" % search, (middle+1))
break
else:
last = int(middle-1)
middle = int((first+last)/2)
Upvotes: 2