首页 > 解决方案 > 我如何证明和分析代码的运行时间,是 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

标签: pythonrecursiontimeruntimetime-complexity

解决方案


起初,我有点怀疑你的算法是否真的在 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) 内运行。


推荐阅读