下面是我用python3版本写的二分查找的完整代码。 我能够:-i) 创建一个列表,ii) 使用冒泡排序算法对列表进行排序,iii) 编写用于使用二进制搜索搜索数字的代码片段, 但是在搜索任何数字(列表中存在/不存在)时,我的代码进入无限循环并且没有给出任何结果。 我尝试查找错误,但无法调试代码。
另外,如何获取列表中数字的索引?我想到了使用 list.index() 方法。它可以在排序列表的情况下工作吗,或者我的索引号输出会被错误显示?
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")
最佳答案
死循环是从线开始
low=mid+1
我想你的意思是
last=mid+1
错误是这样的list[mid]<target
会发生,但是因为low
正在更改而不是 last
, mid
永远不会改变案例将在下一次迭代中再次触发。
编辑:另请注意 mid
是列表中数字的索引
关于python - 如何在 python 中使用二进制搜索算法(不实现任何函数)搜索数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37867530/