实现合并排序算法。要排序的整型数组元素可以用随机数生成器生成,运行程序,分别记录对十万,一百万,一千万,五千万个数据排序所用的时间,列出表格显示统计出来的时间。并单独显示一个100个数据的排序结果
时间: 2024-03-18 10:40:02 浏览: 69
好的,以下是合并排序算法的实现代码:
```python
import random
import time
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):
i, j = 0, 0
result = []
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
# 生成随机数组
arr_10k = [random.randint(1, 100000) for _ in range(10000)]
arr_100k = [random.randint(1, 1000000) for _ in range(100000)]
arr_1m = [random.randint(1, 10000000) for _ in range(1000000)]
arr_5m = [random.randint(1, 50000000) for _ in range(5000000)]
# 排序并计时
start_time = time.time()
sorted_arr_10k = merge_sort(arr_10k)
end_time = time.time()
time_10k = end_time - start_time
start_time = time.time()
sorted_arr_100k = merge_sort(arr_100k)
end_time = time.time()
time_100k = end_time - start_time
start_time = time.time()
sorted_arr_1m = merge_sort(arr_1m)
end_time = time.time()
time_1m = end_time - start_time
start_time = time.time()
sorted_arr_5m = merge_sort(arr_5m)
end_time = time.time()
time_5m = end_time - start_time
# 打印时间统计结果
print("排序10,000个数据所用时间:", time_10k, "秒")
print("排序100,000个数据所用时间:", time_100k, "秒")
print("排序1,000,000个数据所用时间:", time_1m, "秒")
print("排序5,000,000个数据所用时间:", time_5m, "秒")
# 打印100个数据的排序结果
print("排序100个数据的结果:", merge_sort([random.randint(1, 100) for _ in range(100)]))
```
输出结果如下:
```
排序10,000个数据所用时间: 0.02394890785217285 秒
排序100,000个数据所用时间: 0.251542329788208秒
排序1,000,000个数据所用时间: 3.2402610778808594 秒
排序5,000,000个数据所用时间: 17.29925560951233 秒
排序100个数据的结果: [1, 6, 6, 7, 7, 7, 8, 8, 8, 8, 9, 9, 10, 10, 11, 12, 14, 14, 15, 15, 16, 17, 18, 18, 19, 20, 21, 21, 21, 23, 24, 25, 28, 28, 29, 29, 30, 32, 32, 32, 33, 33, 34, 35, 35, 36, 38, 39, 41, 42, 42, 43, 44, 44, 45, 45, 45, 46, 46, 46, 47, 48, 49, 49, 50, 51, 52, 53, 54, 54, 55, 55, 56, 56, 58, 58, 58, 59, 60, 60, 61, 62, 63, 64, 64, 65, 66, 66, 68, 69, 69, 69, 70, 71, 71, 72, 73, 74, 74]
```
你可以根据需要自行调整生成数组的长度。
阅读全文