python二分法查找顺序表

引以为戒

  • python二分法查找顺序表被坑实录
  • 代码1:非递归,二分法查找顺序表(错误)
  • 代码2:非递归,二分法查找顺序表(正确)

python二分法查找顺序表被坑实录

废话不多说上代码,代码1是错的,费了我几十分钟愣是不知道毛病出在哪里,但是程序一直在while死循环,后来才发现竟然少些了两个条件(我以为程序会自动识别,但是程序给我严词拒绝!我可真是个大聪明~)

代码1:非递归,二分法查找顺序表(错误)

def search(alist,item):
    found = False
    first = 0
    last = len(alist)-1
    while first<=last and not found:
        mid = (last+first)//2
        if item==alist[mid]:
            found = True
        elif alist[mid]>item:
                last = mid-1
        else:
                first = mid+1
    return found

代码2:非递归,二分法查找顺序表(正确)

def search(alist,item):
    found = False
    first = 0
    last = len(alist)-1
    while first<=last and not found:
        mid = (last+first)//2
        if item==alist[mid]:
            found = True
        elif alist[mid]>item:
                last = mid-1
                first=first##发现问题了吗老铁?
        else:
                first = mid+1
                last=last##发现问题了吗老铁?
    return found

你可能感兴趣的:(python小记)