https://leetcode-cn.com/submissions/detail/24096646/
class Solution(object):
def sortArray(self, nums):
# ------------------------------------------------------------------------
# Merge时间复杂度:O(len(left)+len(right))=O(n)
def merge(left,right): # Merge空间复杂度:O(len(left)+len(right))=O(n)
i, j = 0, 0
result=[]
while i<len(left) and j<len(right): # 都存在
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
if i < len(left): # left数组存在
result += left[i:]
if j < len(right): # right数组存在
result += right[j:]
return result
def mergeSort(data): # mergeSort时间复杂度:O(nlogn)
if len(data) <= 1: return data
num = len(data)//2
left = mergeSort(data[:num])
right = mergeSort(data[num:])
return merge(left, right) # 合并两个有序表
# ------------------------------------------------------------------------
return mergeSort(nums)
排序类别 | 排序方法 | 时间复杂度 | 空间复杂度 | 稳定性 | 复杂性 | ||
平均情况 | 最坏情况 | 最好情况 | |||||
归并排序 | 归并排序 | O(nlog2n) | O(nlog2n) | O(nlog2n) | O(n) | 稳定 | 较复杂 |