编程完成随机生成20个数,用合并排序进行排序
时间: 2023-07-15 13:14:33 浏览: 79
好的,以下是 Python 代码实现:
```python
import random
# 随机生成20个数
nums = [random.randint(1, 100) for _ in range(20)]
# 合并排序函数
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):
res = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
res.append(left[i])
i += 1
else:
res.append(right[j])
j += 1
res += left[i:]
res += right[j:]
return res
# 打印排序前的数组
print("排序前:", nums)
# 排序
nums_sorted = merge_sort(nums)
# 打印排序后的数组
print("排序后:", nums_sorted)
```
输出结果:
```
排序前: [6, 24, 80, 39, 67, 62, 55, 77, 63, 43, 31, 87, 97, 43, 66, 53, 21, 36, 38, 84]
排序后: [6, 21, 24, 31, 36, 38, 39, 43, 43, 53, 55, 62, 63, 66, 67, 77, 80, 84, 87, 97]
```
阅读全文