MegeSort
def sortIntegers(lst):
if not lst:
temp=[0]*len(lst)
mergeSort(lst,0,len(lst),temp)
# temp为在归并的过程中需要的额外空间
return lst
def mergeSort(lst,start,end,temp):
if end-start<2: #单变量自然有序
return
mid=start+(start-end)//2 #以中点为界
mergeSort(lst,start,end,temp) #对前半段排序
mergeSort(lst,start,end,temp) #对后半段排序
merge(lst,start,end,temp) #二路归并
def merge(lst,start,end,temp):
#归并算法
leftindex=start
midindex=(start+end)//2
rightindex=midindex
tempindex=leftindex
while leftindex<midindex and rightindex<end:
if lst[leftindex]<=lst[rightindex]:
temp[tempindex]=lst[leftindex]
leftindex=leftindex+1
else:
temp[tempindex]=lst[rightindex]
rightindex=rightindex+1
tempindex=tempindex+1
while leftindex<midindex: #如果left里还有数
temp[tempindex]=lst[leftindex]
tempindex=tempindex+1
leftindex=leftindex+1
while rightindex<end: #如果right里还有数
temp[tempindex]=lst[rightindex]
tempindex=tempindex+1
rightindex=rightindex+1
lst[start:end]=temp[start:end]
算法时间复杂度为
O(nlogn)
O
(
n
l
o
g
n
)
:
T(n)=2T(n/2)+O(n)
T
(
n
)
=
2
T
(
n
/
2
)
+
O
(
n
)
QuickSort
def sortIntegers(lst):
if not lst:
return lst
quickSort(lst,0,len(lst)-1)
return lst
def quickSort(lst,start,end):
if start>=end:
return
pivot=lst[(start+end)//2]
left=start
right=end
while left<=right: #<=不是<
while left<=right and lst[left]<pivot:
left=left+1
while left<=right and lst[right]>pivot:
right=right-1
if left<=right:
temp=lst[left]
lst[left]=lst[right]
lst[right]=temp
left=left+1
right=right-1
quickSort(lst,start,right)
quickSort(lst,left,end)