使用Python实现merge sort排序算法,请清晰划分测试程序以及函数定义
时间: 2024-09-09 08:03:01 浏览: 57
在Python中,Merge Sort是一种分治策略的排序算法,其基本思想是将一个大数组分割成两个小数组,分别对它们进行排序,然后合并这两个已排序的小数组。以下是Merge Sort的函数定义和简单的测试程序:
```python
# 定义merge_sort函数
def merge_sort(arr):
if len(arr) <= 1:
return arr
# 分割数组
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
# 递归地对左右半部分进行排序
left_half = merge_sort(left_half)
right_half = merge_sort(right_half)
# 合并两个已排序的部分
return merge(left_half, right_half)
# 定义辅助函数merge
def merge(left, right):
merged = []
left_index = 0
right_index = 0
# 比较并合并两个序列
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
merged.append(left[left_index])
left_index += 1
else:
merged.append(right[right_index])
right_index += 1
# 将剩余部分添加到结果
merged.extend(left[left_index:])
merged.extend(right[right_index:])
return merged
# 测试程序
if __name__ == "__main__":
test_array = [9, 5, 2, 7, 1, 8, 6, 3, 4]
sorted_array = merge_sort(test_array)
print("Sorted array:", sorted_array)
阅读全文
相关推荐

















