用python写个最简短的归并排序代码
时间: 2023-12-18 09:47:42 浏览: 40
下面是一个简单的 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
return arr
```
调用 `merge_sort` 函数即可对一个列表进行归并排序:
```python
arr = [3, 8, 1, 7, 4, 2]
sorted_arr = merge_sort(arr)
print(sorted_arr) # [1, 2, 3, 4, 7, 8]
```
阅读全文