阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。
1. Merge sort
归并拆分/合并轨迹: [38,27,43,3,9,82]拆为[38,27,43]与[3,9,82],继续拆到单元素,再逐层合并为[27,38,43]、[3,9,82],最终[3,9,27,38,43,82]。
TC:拆分+合并
- 拆分:
- 合并:
- 每一层merge:
- 一共多少层:
Total:
SC: recursion层数() + 新建组数() =
- 数组消耗只有,因为系统会回收没用的空间
def merge(list1, list2):
new_list = []
i = 0
j = 0
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
new_list.append(list1[i])
i += 1
else:
new_list.append(list2[j])
j += 1
new_list.extend(list1[i:])
# while i < len(list1):
# new_list.append(list1[i])
# i += 1
new_list.extend(list2[j:])
# while j < len(list2):
# new_list.append(list2[j])
# j += 1
return new_list
def merge_sort(array):
if len(array) == 0 or len(array) == 1:
return array
middle = (len(array) + 1) // 2
left = merge_sort(array[:middle])
right = merge_sort(array[middle:])
return merge(left, right)# Test case
print(merge([2, 3, 4], [1, 5, 6, 7, 10]))
alist = [2, 1, 0, 3, -1, 5]
print(merge_sort(alist))[1, 2, 3, 4, 5, 6, 7, 10]
[-1, 0, 1, 2, 3, 5]
2. Quick sort
partition不变量与例子: [7,2,5,8,3,6]以5为pivot,先交换到末尾,依次把2、3换到store_index左侧,最后将5放到索引2,得到[2,3,5,8,7,6]。左边严格小于pivot,右边大于或等于;store_index应理解为下一个小元素的写入位置。
TC: Average but 非常小概率发生worst case
SC: Average but 非常小概率发生worst case
递归树: 平衡拆分每层总处理O(n)、约log n层;每次只减1的失衡拆分成本为。随机选pivot提供期望界,不消除最坏情况。
结论:平均/期望 、;最坏分别为 、
from random import randrange
def partition(lst, start, end, pivot_index): # TC=O(n), SC=O(1)
lst[pivot_index], lst[end] = lst[end], lst[pivot_index]
store_index = start # 物理意义:store_index左边一定都比pivot小
pivot = lst[end]
for i in range(start, end):
if lst[i] < pivot:
lst[i], lst[store_index] = lst[store_index], lst[i]
store_index += 1
lst[store_index], lst[end] = lst[end], lst[store_index]
return store_index
def quick_sort_helper(lst, start, end):
if start >= end:
return
pivot_index = randrange(start, end + 1) # randrange左闭右开
new_pivot_index = partition(lst, start, end, pivot_index)
quick_sort_helper(lst, start, new_pivot_index - 1)
quick_sort_helper(lst, new_pivot_index + 1, end)
def quick_sort(lst):
quick_sort_helper(lst, 0, len(lst) - 1)# Test case
print(partition([2, 1, 3, 4, 5], 0, 4, 2))
alist = [28, 1, -1, 5]
quick_sort(alist)
print(alist)2
[-1, 1, 5, 28]