python代码写出给定数组a={7,2,1,6,5,4,3,8},使用合并排序算法将数组里面的元素进行从小到大的排序。
时间: 2023-10-30 10:05:55 浏览: 90
下面是使用归并排序算法将数组a从小到大排序的Python代码:
```
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i, j = 0, 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
a = [7, 2, 1, 6, 5, 4, 3, 8]
result = merge_sort(a)
print(result)
```
输出结果为:[1, 2, 3, 4, 5, 6, 7, 8]
阅读全文