试图在python中创建二进制搜索

时间:2015-06-06 02:56:04

标签: python

我尝试创建二进制搜索,但无法让代码适用于数字4,6,7,8和9.有没有人有任何想法?

list = [1,2,3,4,5,6,7,8,9]

search = 3
first = 0
last = (len(list)-1)
found = False

while first <= last and not found:
    mid = (first+last//2)
    if list[mid] == search:
        found = True
   else:
    if search > list[mid]:
        for i in range(mid):
            list.remove(list[0])
        print(list)
    else:
        for i in range(mid):
            last = (len(list)-1)
            list.remove(list[last])
        print(list)

if found == True:
    print("Item found")

1 个答案:

答案 0 :(得分:1)

解决方案本身非常糟糕,你要删除原始列表中的元素,这是不必要的,也浪费时间。此外,该列表无法用于进一步搜索。

试试这个:

list = [1,2,3,4,5,6,7,8,9]
search = 3
first = 0
last = (len(list)-1)
found=False
while first <= last:
    mid = first + (last-first)/2
    if list[mid] == search:
        found=True
        break
    else:
        if search > list[mid]:
                first=mid+1
                print list[first:last+1]
        else:
                last=mid-1
                print list[first:last+1]
if found == True:
    print "Element Found"
else:
    print "Element not found"

更清洁的方式,无需删除任何元素。