基于Python对两种算法时间复杂度的比较
本文是基于对两种简单查找算法的对比
首先,构造两种查找函数
函数一:
def select1(list, x):
n = len(list)
index = 0
while list[index] != x and index < n-1:
index += 1
if index <= n - 1:
print(index)
函数二:
def select2(list, x):
n = len(list)
list.append(x)
index2 = 0
while list[index2] != x:
index2 += 1
if index2 <= n - 1:
print(index2)
两种函数仅在while()循环的条件上有所区别。
其次,构造用于查找的含1000000个元素的随机列表
# the creation of the list
myList = []
for i in range(1000000):
myList.append(random.randint(1, 1000000))
最后使用time模块对两种函数运行时间进行比较
完整代码如下:
import random
import time
# the defination of two
def select1(list, x):
n = len(list)
index = 0
while list[index] != x and index < n-1:
index += 1
if index <= n - 1:
print(index)
def select2(list, x):
n = len(list)
list.append(x)
index2 = 0
while list[index2] != x:
index2 += 1
if index2 <= n - 1:
print(index2)
# the creation of the list
myList = []
for i in range(1000000):
myList.append(random.randint(1, 1000000))
# the charcter need to be selected
x = 555
# the time to be recorded
start_time1 = time.time()
select1(myList, x)
end_time2 = time.time()
select2(myList, x)
end_time3 = time.time()
print("函数一运行的时间", end_time2 - start_time1)
print("函数二运行的时间", end_time3 - end_time2)
运行结果:
结果1:
129364
129364
函数一运行的时间 0.012695074081420898
函数二运行的时间 0.008054971694946289结果2:
999999
函数一运行的时间 0.10183167457580566
函数二运行的时间 0.06033611297607422…
综合分析,函数二在时间复杂度方面优于函数一