两种大数据列表简单查找O(n)算法的比较

基于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

综合分析,函数二在时间复杂度方面优于函数一

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值