自顶向下的归并排序代码
时间: 2024-03-08 20:44:23 浏览: 112
自顶向下的归并排序是一种经典的排序算法,它采用分治的思想将待排序的数组不断地二分,然后将分割后的子数组进行合并,最终得到有序的数组。以下是一个示例的自顶向下的归并排序代码:
```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
while i < len(left):
result.append(left[i])
i += 1
while j < len(right):
result.append(right[j])
j += 1
return result
```
阅读全文