归并排序是面试最常考内容,
让你描述算法,
让你写算法,
让你分析时间复杂度
归并排序merge sort思路:
归并排序中间劈一刀,数组分两半,两边排好序,最后把左右两个合并。就是先局部有序,再整体有序。
时间复杂度
归并排序复杂度最好,最坏,平均都是nlogn。是严格的nlogn复杂度。
空间复杂度
归并排序需要额外的O(N)空间,因为要合并两个数组,不可能在原地合并数组,必须要开辟新的空间来合并
采用了九章算法老师Java版本,直接无脑翻译为了Python版本
class Solution():
def sortIntegers2(self, A):
if not A:
return
temp = [0] * len(A)
return self.mergeSort(A, 0, len(A) - 1, temp)
def mergeSort(self, A, start, end, temp):
if start >= end:
return
#无脑先分为两半
#先递归到左边进行排序
self.mergeSort(A, start, (start + end)//2, temp)
#再递归到右边进行排序
self.mergeSort(A, (start + end)//2 + 1, end, temp)
#合并数组的左右两部分
return self.merge(A, start, end, temp)
#合并两个子数组
def merge(self, A, start, end, temp):
middle = (start + end) // 2
leftIndex = start #左侧子数组指针
rightIndex = middle + 1 #右侧子数组指针
index = leftIndex
# 比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置
while leftIndex <= middle and rightIndex <= end:
if A[leftIndex] < A[rightIndex]:
temp[index] = A[leftIndex]
index += 1
leftIndex += 1
else:
temp[index] = A[rightIndex]
index += 1
rightIndex += 1
#最后有可能剩下一个数组还没有结束
while leftIndex <= middle:
temp[index] = A[leftIndex]
index += 1
leftIndex += 1
while rightIndex <= end:
temp[index] = A[rightIndex]
index += 1
rightIndex += 1
#把临时数组的值依次给
for i in range(start, end+1):
A[i] = temp[i]
#A = temp
return A
obj = Solution()
a = [3,2,1,4,5]
b = obj.sortIntegers2(a)
print(b)
输出:
[1, 2, 3, 4, 5]
[Finished in 0.1s]
网页测试的代码
class Solution():
def sortIntegers2(self, A):
if not A:
return
temp = [0] * len(A)
self.mergeSort(A, 0, len(A) - 1, temp)
def mergeSort(self, A, start, end, temp):
if start >= end:
return
#无脑先分为两半
#先递归到左边进行排序
self.mergeSort(A, start, (start + end)//2, temp)
#再递归到右边进行排序
self.mergeSort(A, (start + end)//2 + 1, end, temp)
#合并数组的左右两部分
self.merge(A, start, end, temp)
#合并两个子数组
def merge(self, A, start, end, temp):
middle = (start + end) // 2
leftIndex = start #左侧子数组指针
rightIndex = middle + 1 #右侧子数组指针
index = leftIndex
while leftIndex <= middle and rightIndex <= end:
if A[leftIndex] < A[rightIndex]:
temp[index] = A[leftIndex]
index += 1
leftIndex += 1
else:
temp[index] = A[rightIndex]
index += 1
rightIndex += 1
#最后有可能剩下一个数组还没有结束
while leftIndex <= middle:
temp[index] = A[leftIndex]
index += 1
leftIndex += 1
while rightIndex <= end:
temp[index] = A[rightIndex]
index += 1
rightIndex += 1
#把临时数组的值依次给
for i in range(start, end+1):
A[i] = temp[i]
#A = temp
https://www.lintcode.com/problem/sort-integers-ii/description
测试通过了
认识你是我们的缘分,同学,等等,学习人工智能,记得关注我。
微信扫一扫
关注该公众号