排序和查找
一、知识概览
本章整体知识点如下:
查找算法知识点如下:
二、代码实现
2.1顺序查找
(1)无序表顺序查找
# 顺序查找
##无序表顺序查找
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]
print(sequentialSearch(testlist, 3))
print(sequentialSearch(testlist, 13))
(2)有序表顺序查找
# ##有序表查找代码
def orderedSequentialSearch(alist, item):
pos = 0
found = False
stop = False
while pos < len(alist) and not found and not stop:
if alist[pos] == item:
found = True
else:
if alist[pos] > item:
stop = True
else:
pos = pos + 1
return found
testlist2 = [0, 1, 2, 8, 13, 17, 19, 32, 42]
print(orderedSequentialSearch(testlist2, 3))
print(orderedSequentialSearch(testlist2, 13))
2.2 二分法查找
(1)普通二分法
# 二分查找
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
testlist3 = [0, 1, 2, 8, 13, 17, 19, 32]
print(binarySearch(testlist3, 3))
print(binarySearch(testlist3, 13))
(2)使用递归的二分查找
符合分而治之的策略,考虑递归法。
# 二分查找递归算法版本
def binarySearch2(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 binarySearch2(alist[:midpoint], item) # 切片操作复杂度是O(K)
else:
return binarySearch2(alist[midpoint + 1:], item)
print(binarySearch2(testlist3, 3))
print(binarySearch2(testlist3, 13))
输出
False
True
False
True
False
True
False
True
下一节学排序啦~~~~