[英]How can I make this python function run O(log n) time instead of O(n) time?
[英]How can I justify and analyze code's running time, is it O(n)?
如何通過遞歸調用證明和分析代碼的運行時間,是否為O(n)?
A = [10,8,7,6,5]
def Algorithm(A):
ai = max(A) # find largest integer
i = A.index(ai)
A[i] = 0
aj = max(A) # finding second largest integer
A[i] = abs(ai - aj) # update A[i]
j = A.index(aj)
A[j] = 0 # replace the A[j] by 0
if aj == 0: # if second largest item equals
return ai # to zero return the largest integer
return Algorithm(A) # call Algorithm(A) with updated A
這是它的細分:
def Algorithm(A):
ai = max(A) # O(n)
i = A.index(ai) # O(n)
A[i] = 0 # O(1)
aj = max(A) # O(n)
A[i] = abs(ai - aj) # O(1)
j = A.index(aj) # O(n)
A[j] = 0 # O(1)
if aj == 0: # O(1)
return ai # O(1)
return Algorithm(A) # recursive call, called up to n times recursively
只要max(A)
不為0
,則調用最后一次遞歸調用,這是n
次,在最壞的情況下,如果所有都是正數。
因此,直到最后一行的所有內容都是O(n)
,並且最后一行使所有內容運行n次,所以總和為O(n^2)
起初,我有點懷疑您的算法是否真正在O(n)中運行。 還有以下程序
import timeit, random
import matplotlib.pyplot as plt
code = """
def Algorithm(A):
ai = max(A) # find largest integer
i = A.index(ai)
A[i] = 0
aj = max(A) # finding second largest integer
A[i] = abs(ai - aj) # update A[i]
j = A.index(aj)
A[j] = 0 # replace the A[j] by 0
if aj == 0: # if second largest item equals
return ai # to zero return the largest integer
return Algorithm(A) # call Algorithm(A) with updated A
Algorithm(%s)
"""
x, y = [], []
lst = [random.randint(-1000, 10000)]
for i in range(1000):
lst.append(random.randint(-1000, 10000))
time = timeit.timeit(stmt=code % lst, number=10)
x.append(i)
y.append(time)
plt.plot(x, y)
plt.show()
為不同的隨機生成的列表測量算法的運行時間(並在之后進行繪制)。 結果
顯然支持非線性增長。 可以這樣說,因為該算法的復雜度為O(n ^ 2),所以無法證明它在O(n)內運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.