#归并排序,先把数组按中间分为2个单元,直至每个单元仅包含1个元素,然后依次合并2个单元至一临时数组
def Merge(str,start_index,end_index,mid,temp):
j=start_index
k=mid+1
i=0
while j<=mid and k<=end_index:
if str[j]<str[k]:
temp[i]=str[j] #小的放前面
j+=1
else:
temp[i]=str[k]
k+=1
i+=1
while j<=mid:
temp[i]=str[j]
j+=1
i+=1
while k<=end_index:
temp[i]=str[k]
k+=1
i+=1
for s in range(0,i):
str[start_index+s]=temp[s]
def MergeSort(str,start_index,end_index,temp):
if start_index<end_index:
mid=(start_index+end_index)//2
MergeSort(str,start_index,mid,temp)
MergeSort(str,mid+1,end_index,temp)
Merge(str,start_index,end_index,mid,temp)
def Merge1(str,start_index,end_index,mid):
j=start_index
k=mid+1
i=0
temp=[d for d in range(len(str))]
while j<=mid and k<=end_index:
if str[j]<str[k]:
temp[i]=str[j]
j+=1
else:
temp[i]=str[k]
k+=1
i+=1
while j<=mid:
temp[i]=str[j]
j+=1
i+=1
while k<=end_index:
temp[i]=str[k]
k+=1
i+=1
for s in range(0,i):
str[start_index+s]=temp[s]
def MergeSort1(str,start_index,end_index):
if start_index<end_index:
mid=(start_index+end_index)//2
MergeSort1(str,start_index,mid)
MergeSort1(str,mid+1,end_index)
Merge1(str,start_index,end_index,mid)
str=[49,27,49,3,38,1,13,76,97,65]
temp=[d for d in range(len(str))]
beginTime=time.clock()
MergeSort(str,0,len(str)-1,temp)
endTime=time.clock()
print("归并排序 临时数组递归前初始化好")
print(str)
print(endTime-beginTime)
str=[49,27,49,3,38,1,13,76,97,65]
beginTime=time.clock()
MergeSort1(str,0,len(str)-1)
endTime=time.clock()
print("归并排序1 临时数组在merge时创建")
print(str)
print(endTime-beginTime)
def Merge(str,start_index,end_index,mid,temp):
j=start_index
k=mid+1
i=0
while j<=mid and k<=end_index:
if str[j]<str[k]:
temp[i]=str[j] #小的放前面
j+=1
else:
temp[i]=str[k]
k+=1
i+=1
while j<=mid:
temp[i]=str[j]
j+=1
i+=1
while k<=end_index:
temp[i]=str[k]
k+=1
i+=1
for s in range(0,i):
str[start_index+s]=temp[s]
def MergeSort(str,start_index,end_index,temp):
if start_index<end_index:
mid=(start_index+end_index)//2
MergeSort(str,start_index,mid,temp)
MergeSort(str,mid+1,end_index,temp)
Merge(str,start_index,end_index,mid,temp)
def Merge1(str,start_index,end_index,mid):
j=start_index
k=mid+1
i=0
temp=[d for d in range(len(str))]
while j<=mid and k<=end_index:
if str[j]<str[k]:
temp[i]=str[j]
j+=1
else:
temp[i]=str[k]
k+=1
i+=1
while j<=mid:
temp[i]=str[j]
j+=1
i+=1
while k<=end_index:
temp[i]=str[k]
k+=1
i+=1
for s in range(0,i):
str[start_index+s]=temp[s]
def MergeSort1(str,start_index,end_index):
if start_index<end_index:
mid=(start_index+end_index)//2
MergeSort1(str,start_index,mid)
MergeSort1(str,mid+1,end_index)
Merge1(str,start_index,end_index,mid)
str=[49,27,49,3,38,1,13,76,97,65]
temp=[d for d in range(len(str))]
beginTime=time.clock()
MergeSort(str,0,len(str)-1,temp)
endTime=time.clock()
print("归并排序 临时数组递归前初始化好")
print(str)
print(endTime-beginTime)
str=[49,27,49,3,38,1,13,76,97,65]
beginTime=time.clock()
MergeSort1(str,0,len(str)-1)
endTime=time.clock()
print("归并排序1 临时数组在merge时创建")
print(str)
print(endTime-beginTime)