分治算法
简介
将一个问题分解为多个相似的可以求解的子问题
分治与递归的关系
递归 ⊆ {\subseteq} ⊆迭代
应用
01归并排序
def mergeSort(alist):
if len(alist) > 1:
mid = len(alist)//2
lefthalf = alist[:mid]
righalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i = 0
j = 0
k = 0
while i < len(lefthalf) and len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k] = lefthalf[i]
i +=1
else:
alist[k] = righthalf[j]
j += 1
k += 1
while i < len(lefthalf):
alist[k] = lefthalf[i]
i = i +1
k = k +1
while j < len(righthalf):
alist[k] = righthalf[j]
j = j + 1
k = k + 1
02二分查找
#二分法循环实现
def binarySearch(alist,data):
first = 0
last = len(alist) - 1
found = False
while first <= last and not found:
mid = (first + last) // 2 #取中间值
if alist[mid] == data:
found = True
else:
if alist[mid] > data;
first = mid +1 #右边序列
else:
last = mid - 1 #左边序列
return found
#递归法实现
def binarySearch(alist,data):
if len(alist) == 0:
return False #基本情况,即列表中不存在要搜索的目标元素
else:
mid = len(alist) // 2
if alist[mid] == data:
return True
else:
if data < alist[mid]:
return binarySearch(alist[:mid],data)
else:
return binarySearch(alist[mid+1:],data)
⚠️笔者最近忙于复习,准备考试,测试结果一项留待考试后完善