用Python实现归并排序
时间: 2023-06-29 08:18:26 浏览: 84
python 实现归并排序算法
5星 · 资源好评率100%
当然可以,下面是一个简单的 Python 归并排序实现:
```python
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i = j = k = 0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1
while i < len(left_half):
arr[k] = left_half[i]
i += 1
k += 1
while j < len(right_half):
arr[k] = right_half[j]
j += 1
k += 1
arr = [5, 2, 8, 4, 7, 1, 3, 6]
merge_sort(arr)
print(arr)
```
输出结果为 `[1, 2, 3, 4, 5, 6, 7, 8]`。
阅读全文