1,查找算法
常用的查找算法包括顺序查找,二分查找和哈希查找。
1.1 顺序查找(Sequential search)
顺序查找: 依次遍历列表中每一个元素,查看是否为目标元素。python实现代码如下:
#无序列表 def sequentialSearch(alist,item): found = False pos=0 while not found and pos<len(alist): 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)) #有序列表(升序) def orderedSequentialSearch(orderedList,item): found = False pos = 0 stop = False while not found and not stop and pos<len(orderedList): if orderedList[pos]==item: found=True else: if orderedList[pos]>item: stop=True else: pos = pos+1 return found testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,] print(orderedSequentialSearch(testlist, 3)) print(orderedSequentialSearch(testlist, 13))