使用python递归实现归并排序
时间: 2024-03-30 16:32:23 浏览: 65
python实现归并排序算法
以下是使用Python递归实现归并排序的代码[^1]:
```python
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)
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
while i < len(left):
result.append(left[i])
i += 1
while j < len(right):
result.append(right[j])
j += 1
return result
# 示例
arr = [29, 7, 70, 42, 90, 3, 87, 8, 30, 5]
sorted_arr = merge_sort(arr)
print(sorted_arr) # 输出:[3, 5, 7, 8, 29, 30, 42, 70, 87, 90]
```
阅读全文