Algorithm 非递归算法的效率分析
我试图分析一个算法,用5个步骤来估计它的时间效率 这五个步骤是: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
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
我的解决方法是:
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
我做得对吗?我认为应该通过以下方式解决这个问题:
这意味着我们的最坏情况是以O(n^2)为界的。
我们的平均病例是通过将所有可能的结果相加并除以所有结果来计算的。这看起来非常类似于C(n)的求和。输入长度为n时,运行可能需要的时间总和为:
这就是θ(n^2)
最后,最佳案例时间。这几乎是微不足道的。这里最好的情况是数组中的第一项和第二项相同。这是常数时间,所以最好的情况是θ(1)
希望这有帮助 数组索引是基于0还是基于1?下定决心@n、 对不起,以0为基础。修好了。