核心思想:将数组不断的分成两组,当组内只有一个元素时,这个组便是有序数组,然后再合并有序数组。
def merge(array,start,mid,end):
temp = []
i,j = start , mid+1
while (i<= mid and j<=end):
if array[i] >= array[j]:
temp.append(array[j])
j+=1
else:
temp.append(array[i])
i+=1
while(i<= mid):
temp.append( array[i])
i+=1
while(j<=end):
temp.append( array[j])
j+=1
print start
print array
print temp
for i in range(0,len(temp)):
array[start+i] = temp[i]
def merge_sort(array,start,end):
if(start<end):
mid = (start + end)/2
merge_sort(array,start,mid)
merge_sort(array,mid+1,end)
merge(array,start,mid,end)
if __name__ == "__main__":
array = [2,1,3,3,6,5,4]
merge_sort(array,0,len(array)-1)
print array