[英]time complexity : why O(nlogn)?
I have a document that says the average case time-complexity for the given code is O(nlog 2 n) 我有一个文档说明给定代码的平均时间复杂度为O(nlog 2 n)
Random r = new Random();
int k = 1 + r.nextInt(n);
for (int i = 0; i < n ; i += k);
I have computed the best and worst cases as: 我计算了最好和最坏的情况:
Best case, k = n
leading to time complexity of O(1)
. 最好的情况,
k = n
导致O(1)
时间复杂度。
Worst case, k = 1
leading to time complexity of O(n)
. 最坏的情况是,
k = 1
导致O(n)
时间复杂度。
How can average case be O(nlog 2 n), which is higher than the worst case. 平均情况如何是O(nlog 2 n),这高于最坏情况。 Am I missing something?
我错过了什么吗?
Edit: The document could be prone to mistakes, so in that case what would be the average time-complexity of the above code, and why?
编辑:文档可能容易出错,所以在这种情况下,上述代码的平均时间复杂度是什么,为什么?
For a given value of k, the for loop runs n/k times. 对于给定的k值,for循环运行n / k次。 (I'm ignoring rounding, which makes the analysis a bit more complicated but doesn't change the result).
(我忽略了舍入,这使得分析更复杂但不会改变结果)。
Averaging over all values of k gives: (n/1 + n/2 + n/3 + ... + n/n) / n. 对所有k值求平均得出:(n / 1 + n / 2 + n / 3 + ... + n / n)/ n。 That's the n'th harmonic number .
那是第n个谐波数 。 The harmonic numbers tend to log(n).
谐波数倾向于log(n)。
Thus the average runtime complexity of this code is log(n). 因此,此代码的平均运行时复杂性为log(n)。 That's O(log n) or equivalently O(log_2 n).
那是O(log n)或等价O(log_2 n)。
Perhaps your book had an additional outer loop that ran this code n times? 也许你的书有一个额外的外循环,运行这段代码n次?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.