Below is my complete code for binary search written in python3 version. I was able to:-i) create a list, ii) sorted the list using bubble sort algorithm, iii)wrote code snippet for searching a number using binary search, But while searching for any number (which is present/not present in the list), my code goes into an infinite loop and does not gives any result. I tried looking for the error,But was unable to debug the code.
Also, how to get the index of the number in list? I thought of using list.index() method. Can it work in case of sorted list or my index number output will be wrongly displayed?
list=[]
item=0
while item!="99":
item=input("Enter the number, To discontinue enter 99:")
if item.isdigit(): #isdigit() checks whether input string consists of digits only
list.append(int(item)) #convert the input string into number
else:
list.append(item)
del list[-1] #Delete the number at last index of the list. It will delete "99",
#which we have used to discontinue the loop
print("The unsorted list is: ",list)
#Using bubble sort algorithm to sort the list
length=len(list)
for i in range(length):
for j in range(length-1):
if list[j]>list[j+1]:
list[j],list[j+1]=list[j+1],list[j]
print("Our sorted list is: ",list)
#Implementing binary serach algorithm
target=int(input("Enter the number you are looking for: "))
first=0 #First index of list is 0
last=len(list)-1 #Last index of list is "length of list minus 1"
mid=(first+last)//2
while first<=last:
if list[mid]<target: #If element at middle index is less than the target element,shift new lower index to one more than middle index
low=mid+1
elif list[mid]==target: #else, if element at middle index is same as target element
print("Number is found at index")
break
else:
last=mid-1
mid=(first+last)//2
if (first>last):
print("Number not found in list")
firstand sometimeslowin your code. Probably the origin of the bug. Choose which it is and rename the other.