【发布时间】:2019-04-20 16:29:24
【问题描述】:
如何证明和分析递归调用代码的运行时间,是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
【问题讨论】:
-
你能描述一下这个函数应该做什么吗?是对列表进行排序吗?它似乎比
O(n)更大,因为对max()和index()的调用都需要O(n)时间。因此,如果此递归调用完成n次,它将是O(n^2)
标签: python recursion time runtime time-complexity