首页 > 解决方案 > 排序功能的时间,python 3

问题描述

如果我有一个已经排序的列表,并且我在列表末尾添加了另一个项目(不一定已排序),排序需要多长时间才能再次对该列表进行排序?

list1 = [1, 2, 3, 5]
list1.append(4)
list1.sort()

标签: pythonpython-3.xsorting

解决方案


使用 BeamsAdept 的示例,您还可以执行两者来比较性能。

 
import time

#WITHOUT SORT 
start_time = time.time()

list1 = []
n = 100000
for i in range(n):
    list1.append(random.randint(1, 1000))

print("Execution time : " + str((time.time() - start_time)))


#SORTING
start_time = time.time()

list1 = []
for i in range(n):
    list1.append(random.randint(1, 1000))
    list1.sort()

print("Execution time sorting : " + str((time.time() - start_time)))

返回例如:

Execution time : 0.123291015625
Execution time sorting : 58.519288063049316

推荐阅读