def merge_sort(array):
"""
归并排序,将数组分为左右两部分,然后先对两部分分别进行归并排序.
归并排序完成后,左右将各有序,然后建立一个新的用来储存结果的数组,遍历左右部分,依次将最小的树加到新数组中
:param array:
:return:
"""
if len(array) == 1:
return array
i = len(array) // 2
array_1 = merge_sort(array[:i])
array_2 = merge_sort(array[i:])
new_array = []
for k in array_1:
m = 0
for j in array_2:
if k > j:
m += 1
new_array.append(j)
else:
break
array_2 = array_2[m:]
new_array.append(k)
for k in array_2:
new_array.append(k)
return new_array
a = [1, 5, 3, 2, 45, 23, 1, 78, 214, 56, 3213, 54, 812]
print('归并排序:', merge_sort(a))
a.sort()
print('系统排序:', a)
网友评论