我需要一些帮助来分析我的算法以确定其理论运行时间。我想我理解如何分析它的大部分内容。我不确定如何分析包含 for循环的 while循环。我会提供我的算法,然后是我的想法/知道。
def getD(a):
corrections = [] #list for correction values
comparisons = 0 #comparison counter
#initialize corrections list with all 0's
for i in range(0,len(a)):
corrections.append(0)
flag = True #loop control
while(flag):
flag = False
#loop through list
for i in range(0,len(a)-1):
current = a[i] #current element value
nxt = a[i+1] #next element value
dif = nxt - (current + 1)
#correct the nxt item.. i+1. comparisons++
if(dif < 0):
comparisons += 1
corrections[i+1] -= dif
a[i+1] -= dif
flag = True
d = int((max(corrections)+1)/2)
#balance the corrections
for i in range(len(a)):
corrections[i] -= d
print(d)
print("Number of comparisons:",comparisons)
n =输入列表的长度(a)
主导操作是3 for for循环和while循环。
第一个 for循环迭代n次..所以它的运行时间为 n。
最后一个for循环也会迭代n次..将修正应用于每个元素,因此它的运行时间 n。
对于上面的2 for循环 ..我认为合并的运行时间是2n?但是要为整个算法运行时间添加更多内容。
在这里,我开始挣扎:
剩下的主导操作(我相信)是而循环,其中为循环。 for 循环将运行最多 n-1次。但是如果不是&lt; 0,它再次以i = 0开始运行for循环。
我不确定这部分的运行时间是什么,也不确定算法的整体运行时间。如何用最后一个for循环计算while?我如何将它们组合在一起?
答案 0 :(得分:2)
你的第一个for
循环总是运行n次迭代,因此是O(n)。
你的上一个for
循环总是运行n次迭代,因此是O(n)。
你的中间for
循环(在while
循环内)总是运行n - 1次迭代,因此是O(n)。
现在,while
循环执行多少次迭代?它似乎是可变的,但让我们仔细看看内部for
循环:
for i in range(0,len(a)-1):
current = a[i] #current element value
nxt = a[i+1] #next element value
dif = nxt - (current + 1)
#correct the nxt item.. i+1. comparisons++
if(dif < 0):
comparisons += 1
corrections[i+1] -= dif
a[i+1] -= dif
flag = True
因此,在第一次通过此for
循环时,i == 0
。 if
语句通过在必要时设置a[1] ≥ a[0] + 1
来确保a[1] = a[0] + 1
。
在第二遍i == 1
。 if
语句通过在必要时设置a[2] ≥ a[1] + 1
来确保a[2]
。
在第三关,i == 2
。 if
语句通过在必要时设置a[3] ≥ a[2] + 1
来确保a[3]
。
请注意,在每次传递时,循环都可以设置a[i+1]
,但不能设置更早的元素。因此,每次通过内部for
循环都不能撤消先前传递的工作。
当此内部for
循环停止执行时,所有a[i+1] ≥ a[i] + 1
都会i
。
while
循环保证至少运行一次。如果内部for
循环对数组进行任何更改,则会设置flag
,使while
循环再次执行。在第二次通过while
循环时,数组已经完全整理,因此flag
将保持False
。
因此while
循环最多执行两次迭代,因此它是O(2n)(n来自内部for
循环的O(n)复杂度)。你可能知道O(2n)== O(n)。
getD
函数中的所有外部循环都是O(n),因此您的函数本身就是O(n)。
顺便说一句,您可以在Python中初始化corrections
:
corrections = [0] * len(a)