Algorithm 非递归算法的效率分析

Algorithm 非递归算法的效率分析,algorithm,for-loop,Algorithm,For Loop,我试图分析一个算法,用5个步骤来估计它的时间效率 这五个步骤是: Algorithm UniqueElements (A[0 … n-1) – //Check whether all the elements in a given array are distinct – //Input: an array A[0 … n] – //Output: returns “true” if all the elements in A are distinct and “false” otherwise

我试图分析一个算法,用5个步骤来估计它的时间效率

这五个步骤是:

Algorithm UniqueElements (A[0 … n-1)
– //Check whether all the elements in a given array are
distinct
– //Input: an array A[0 … n]
– //Output: returns “true” if all the elements in A are
distinct and “false” otherwise
for i ← 0 to n - 2 do
 for j ← i + 1 to n - 1 do
– If A[i] = A[j] return false
return true
  • 决定表示输入大小的参数n
  • 识别算法的基本操作
  • 确定大小为n的输入的最坏、平均和最佳情况
  • 为C(n)反射算法的循环设置求和 结构
  • 简化求和
  • 算法是:

    Algorithm UniqueElements (A[0 … n-1)
    – //Check whether all the elements in a given array are
    distinct
    – //Input: an array A[0 … n]
    – //Output: returns “true” if all the elements in A are
    distinct and “false” otherwise
    for i ← 0 to n - 2 do
     for j ← i + 1 to n - 1 do
    – If A[i] = A[j] return false
    return true
    
    我的解决方法是:

    Algorithm UniqueElements (A[0 … n-1)
    – //Check whether all the elements in a given array are
    distinct
    – //Input: an array A[0 … n]
    – //Output: returns “true” if all the elements in A are
    distinct and “false” otherwise
    for i ← 0 to n - 2 do
     for j ← i + 1 to n - 1 do
    – If A[i] = A[j] return false
    return true
    
  • 因为我只决定输入大小,所以选择了6
  • 我说过算法的基本运算是A[I]=A[j]之间的比较
  • 最佳情况:n=1。最坏情况=6。平均病例=3例
  • 总结:
  • 总和将简化为n^2

  • 我做得对吗?

    我认为应该通过以下方式解决这个问题:

  • 决定参数n。 我想这是问方程中的‘n’是什么。这里是输入数组的长度

  • 我同意基本操作。比较A[i]==A[j]

  • 由于如果两个元素相同,该算法会提前中断,因此我们知道最坏的情况是所有元素都不同。在这种情况下,我们有两个循环——一个嵌套在另一个中——每个循环都与输入长度(n)线性相关。
    这意味着我们的最坏情况是以O(n^2)为界的。

    我们的平均病例是通过将所有可能的结果相加并除以所有结果来计算的。这看起来非常类似于C(n)的求和。输入长度为n时,运行可能需要的时间总和为:
    这就是θ(n^2)

    最后,最佳案例时间。这几乎是微不足道的。这里最好的情况是数组中的第一项和第二项相同。这是常数时间,所以最好的情况是θ(1)

  • 对于这一部分,请再次参考链接数学

  • 我同意你的简化!n^2是正确的


  • 希望这有帮助

    数组索引是基于0还是基于1?下定决心@n、 对不起,以0为基础。修好了。