用递归算法实现归并排序,在主函数中输入一些数据,并通过该递归函数进行排序,并将排序结果输出。
时间: 2024-03-31 22:11:07 浏览: 49
以下是Python代码实现:
```
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
left = merge_sort(left)
right = merge_sort(right)
return merge(left, 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__':
arr = [5, 3, 8, 6, 2, 7, 1, 4]
print("原始数据:", arr)
sorted_arr = merge_sort(arr)
print("排序结果:", sorted_arr)
```
输出结果为:
```
原始数据: [5, 3, 8, 6, 2, 7, 1, 4]
排序结果: [1, 2, 3, 4, 5, 6, 7, 8]
```
阅读全文