from __future__ import print_function
def merge_sort(collection):
"""
二路归并排序(稳定排序),结果升序
算法思想:
二路归并排序主旨是“分解”与“归并”
分解:
1.将一个数组分成两个数组,分别对两个数组进行排序。
2.循环第一步,直到划分出来的“小数组”只包含一个元素,
只有一个元素的数组默认为已经排好序。
归并:
1.将两个有序的数组合并到一个大的数组中。
2.从最小的只包含一个元素的数组开始两两合并。此时,合并
好的数组也是有序的。
Examples:
>>> merge_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> merge_sort([])
[]
>>> merge_sort([-2, -5, -45])
[-45, -5, -2]
"""
length = len(collection)
if length > 1:
midpoint = length // 2
#递归处理前半段
left_half = merge_sort(collection[:midpoint])
#递归处理后半段
right_half = merge_sort(collection[midpoint:])
i = 0
j = 0
k = 0
left_length = len(left_half)
right_length = len(right_half)
#比较这两段,小的元素先放入结果数组
while i < left_length and j < right_length:
if left_half[i] < right_half[j]:
collection[k] = left_half[i]
i += 1
else:
collection[k] = right_half[j]
j += 1
k += 1
#如果左半段没有处理完,则直接放入结果数组
while i < left_length:
collection[k] = left_half[i]
i += 1
k += 1
#如果右半段没有处理完,则直接放入结果数组
while j < right_length:
collection[k] = right_half[j]
j += 1
k += 1
return collection
if __name__ == '__main__':
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
user_input = raw_input('输入待排序的数,用\",\"分隔:\n').strip()
#strip() 方法用于移除字符串头尾指定的字符(默认为空格)
unsorted = [int(item) for item in user_input.split(',')]
print(merge_sort(unsorted))
二路归并排序——python
最新推荐文章于 2023-08-27 14:30:30 发布