算法:归并排序
思想:分治法【问题分解,归并排序递归解决,合并解】
实现:将数组通过递归方式自顶向下的分解至最小单元,再自底向上进行合并,以此实现排序
时间复杂度: Θ ( n l g n ) \Theta(nlgn) Θ(nlgn)
import mathdef merge(nums, p, q, r): #用于将两个已排序好的数组合到一起;合并函数调用次数:n-1print([p, q, r], nums[p:q], nums[q:r])left = nums[p:q]right = nums[q:r]left.append(float('inf')) #极大值作为哨兵-简化代码right.append(float('inf'))i, j = 0, 0for k in range(p, r):if left[i] <= right[j]:nums[k] = left[i]i += 1else:nums[k] = right[j]j += 1print(nums, '\n')def merge_sort(nums, p, r):if r - p > 1: # 当为1时,表明数组为最小单元,即数组中仅有一个元素,已排序好了q = math.floor((p + r) / 2) #划分索引merge_sort(nums, p, q)merge_sort(nums, q, r)merge(nums, p, q, r)if __name__ == '__main__':nums = [5, 2, 7, 4, 1, 3, 2, 6]merge_sort(nums, 0, len(nums)) # 随意指定数组起始和终止索引print(nums)
print值:
[0, 1, 2] [5] [2]
[2, 5, 7, 4, 1, 3, 2, 6] [2, 3, 4] [7] [4]
[2, 5, 4, 7, 1, 3, 2, 6] [0, 2, 4] [2, 5] [4, 7]
[2, 4, 5, 7, 1, 3, 2, 6] [4, 5, 6] [1] [3]
[2, 4, 5, 7, 1, 3, 2, 6] [6, 7, 8] [2] [6]
[2, 4, 5, 7, 1, 3, 2, 6] [4, 6, 8] [1, 3] [2, 6]
[2, 4, 5, 7, 1, 2, 3, 6] [0, 4, 8] [2, 4, 5, 7] [1, 2, 3, 6]
[1, 2, 2, 3, 4, 5, 6, 7] [1, 2, 2, 3, 4, 5, 6, 7]