Python递归实现归并排序算法

2023-04-15 00:00:00 算法 递归 归并

"""
归并排序(递归实现)
"""
def merge_sort(array):
if len(array) == 1:
return array
mid = len(array) // 2
left = array[:mid]
right = array[mid:]
return merge(merge_sort(left), merge_sort(right))
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
if name == "main":
array = [6, 5, 3, 1, 8, 7, 2, 4]
result = merge_sort(array)
print(result)
str_array = ["pidancode.com", "hello", "world", "皮蛋编程", "python"]
result = merge_sort(str_array)
print(result)

相关文章