二分法查找(自定义函数)—python

顺序查找法

自己写函数

(可以但没必要)

def sequentialSearch(alist,item):
    pos = 0
    found =False#这个可以

    while pos <len(alist) and not found:
        if alist[pos] == item:
            found = True
        else:
            pos = pos+1

    return found

testlist = [1,2,32,8,17,19,42,13,0]

print(sequentialSearch(testlist,3))
print(sequentialSearch(testlist,13))

python自带的查找功能

判断值是否在列表里,字符串也同样可以

3 in testlist
Out[3]: False
13 in testlist
Out[4]: True

统计指定值在列表中出现的次数

testlist.count(3)
Out[5]: 0
testlist.count(13)
Out[6]: 1

查看指定值在列表中的位置

testlist.index(13)
Out[8]: 7

二分法查找

使用条件是有序表

非递归

'''
二分查找
'''
def binarySearch(alist,item):
    first = 0
    last = len(alist)-1
    found = False

    while first<=last and not found:
        midpoint = (first+last)//2
        if alist[midpoint] == item:
            found = True
        else:
            if item<alist[midpoint]:
                last = midpoint - 1
            else:
                first = midpoint + 1

    return found

testlist = [0,1,2,8,13,17,19,32,42]
print(binarySearch(testlist,3))
print(binarySearch(testlist,13))

递归

#递归
def binarySearch(alist,item):
    if len(alist)==0:
        return False

    else:
        midpoint = len(alist)//2
        if alist[midpoint] == item:
            return True
        else:
            if item<alist[midpoint]:
                return binarySearch(alist[:midpoint],item)
            else:
                return binarySearch(alist[midpoint+1:],item)

你可能感兴趣的:(数据结构与算法,python)