python - 如何在 python 中使用二进制搜索算法(不实现任何函数)搜索数字

标签 python algorithm search binary

下面是我用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/

相关文章:

python - 在子列表中将字符串转换为 int - python

java - TCP 套接字客户端将输出写入本地主机的速度很慢

c++ - 分而治之真的能战胜增加的内存分配吗?

python - 如何将带有 2 个参数的类字典复制到 2 个列表中

python - 尝试在某位 friend 的计算机上安装Python时出错

algorithm - 最小列总和差异是多少?

algorithm - 有效地绘制星图

algorithm - 在序言中,您如何表示对象执行的状态转换和操作?

iOS MKLocalSearchRequest 排除企业

为未排序的通用数组创建通用搜索函数