python - 合并排序算法排序时间和交换计数
问题描述
我创建了一个程序,其中为列表/数组随机生成数字。在这个列表中,我需要计算排序列表需要多长时间以及排序需要的交换次数。
以下是我的代码。该代码解决了列表没有任何问题,但时间和交换计数器无法正常工作,它只是给了我0,1,1,1,2,1,1,0,2,4
类似的结果。
添加到count
以及在start.time and end.time
import random
import time
#X--------------------------------------------------------------------------------------------------------------------------------------------------------------------
# Random Number Generator
def random_generator():
randomNumber = random.randint(0, 1000)
return randomNumber
#X--------------------------------------------------------------------------------------------------------------------------------------------------------------------
def arraygenerator():
arr = []
for draw in range(15):
randomNumber = random_generator()
arr.append(randomNumber)
print ("Unsorted Array is : ", arr)
return arr
def counter(count):
return count
def merge(S1, S2, S):
start = time.time()
count = 0
i = j = 0
while i + j < len(S):
if j == len(S2) or (i < len(S1) and S1[i] < S2[j]):
S[i+j] = S1[i]
i += 1
count +=1
else:
S[i+j] = S2[j]
j += 1
end = time.time()
print(f"Runtime of the program is {end - start}")
print(counter(count))
def merge_sort(S):
n = len(S)
if n < 2:
return
mid = n // 2
S1 = S[0:mid]
S2 = S[mid:n]
merge_sort(S1)
merge_sort(S2)
merge(S1, S2, S)
def main():
print('The list S1 to be sorted.....')
s1 = arraygenerator()
merge_sort(s1)
print('The sorted list is ', s1)
main()
当我运行代码时,我的输出是
The list S1 to be sorted.....
Unsorted Array is : [697, 126, 983, 400, 400, 583, 166, 343, 517, 819, 265, 193, 362, 993, 876]
Runtime of the program is 0.0
1
Runtime of the program is 0.0
1
Runtime of the program is 0.0
1
Runtime of the program is 0.0
1
Runtime of the program is 0.0
2
Runtime of the program is 0.0
3
Runtime of the program is 0.0
1
Runtime of the program is 0.0
1
Runtime of the program is 0.0
2
Runtime of the program is 0.0
1
Runtime of the program is 0.0
1
Runtime of the program is 0.0
2
Runtime of the program is 0.0
4
Runtime of the program is 0.0
7
The sorted list is [126, 166, 193, 265, 343, 362, 400, 400, 517, 583, 697, 819, 876, 983, 993]
解决方案
推荐阅读
- javascript - 日期字段的 JQuery 验证
- node.js - 将每个初始变量放入 Node 序列化程序中?
- java - WLST - 每个服务器节点的 JVM 参数转储
- python - 使用多个流写入一个文件
- django - 使用 Django Activity Stream 获取按动词过滤的所有动作
- markdown - 从 Markdown 采购时在 Sphinx 中创建表格
- asp.net-mvc - 多个属性值的模型绑定 MVC
- mobile - 将联系人从 CRM 导出到网络文件夹 (IIS) 并在移动设备上显示
- scala - 在 sbt 项目中导入 maven 存储库
- bash - Bash 配置文件变量