我正在创建一个程序来测量各种排序算法(选择,冒泡,合并和树排序)的执行时间。
用于测试用例的列表大小应从10,000开始,每次测试增加10,000,直到测试的执行时间超过60秒。
这就是我的问题。
我有这个可能非常错误(和丑陋)的代码,我已经创建了(我目前只使用冒泡排序进行测试)。
import random
import time
def bubbleSort(a_list):
for passnum in range(len(a_list)-1,0,-1):
for i in range(passnum):
if a_list[i]>a_list[i+1]:
temp = a_list[i]
a_list[i] = a_list[i+1]
a_list[i+1] = temp
a_list = []
for i in range(10000):
a_list.append(random.randrange(0,10000))
start = time.perf_counter()
bubbleSort(a_list)
end = time.perf_counter()
elapsed = end - start
print("{0:.8f}".format(elapsed, "\n"))
print(a_list)
if elapsed <= 60:
for i in range(len(a_list), len(a_list)+10000):
a_list.append(random.randrange(len(a_list)+10000))
start = time.perf_counter()
bubbleSort(a_list)
end = time.perf_counter()
elapsed = end - start
print("{0:.8f}".format(elapsed, "\n"))
print(a_list)
else:
#it'll quit
我很抱歉非常明显的无知。
上面是我的第一反应。然后我想出了这个循环:
start = time.perf_counter()
while start <= 60:
for i in range(len(a_list)+10000):
a_list.append(random.randrange(len(a_list)+10000))
bubbleSort(a_list)
end = time.perf_counter()
elapsed = end - start
print("{0:.8f}".format(elapsed, "\n"))
print(a_list)
如果有人能够推动我朝着正确的方向努力并帮助我思考其背后的逻辑,我将非常感激。非常感谢你。
答案 0 :(得分:0)
首先,折叠一些代码以提高可读性:
a, b = b, a
代码:
import random
import time
def bubbleSort(a_list):
for passnum in range(len(a_list)-1,0,-1):
for i in range(passnum):
if a_list[i] > a_list[i+1]:
a_list[i], a_list[i+1] = a_list[i+1], a_list[i]
elapsed = 0
size = 0
size_inc = 10000
print("Size\tTime")
while elapsed < 60:
# Add 10,000 numbers to the list
size += size_inc
a_list = [random.randrange(0,size) for i in range(size)]
start = time.perf_counter()
bubbleSort(a_list)
end = time.perf_counter()
elapsed = end - start
print(size, "\t{0:.8f}".format(elapsed, "sec.\n"))
输出:
Size Time
10000 12.05934826
20000 47.99201040
30000 111.39582218