简体   繁体   English

时间复杂度:为什么O(nlogn)?

[英]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.

相关问题 这是使用 HeapSort 的 O(nlogn) 的时间复杂度吗 - Is this time complexity of O(nlogn) using HeapSort 解释为什么这个二叉树遍历算法具有O(NlogN)时间复杂度? - Explain why this binary tree traversal algorithm has O(NlogN) time complexity? 时间复杂度 O(nlogn) 是多少? 我错过了什么吗? - How is the the time complexity O(nlogn)? Am I missing something? 是否可以重写代码,使时间复杂度为 O(nlogn)? - Is it possible to rewrite the code so the time complexity is O(nlogn)? 如何合并使用O(nlogn)时间和O(1)空间复杂度对链接列表进行排序 - How to Merge sort a Linked List with O(nlogn) time and O(1) space complexity 可以将InsertionSort复杂度降低到O(nlogn)吗? - Can InsertionSort complexity be brought down to O(nlogn)? 为什么在此Mergesort程序中时间复杂度如此不规则,应随nlogn图严格增加 - Why is Time complexity so irregular in case of this Mergesort program which should be strictly increasing with nlogn graph 为什么 2 for 循环的时间复杂度不是 O(n*2^n)? - Why is the time complexity of 2 for loops not O(n*2^n)? 为什么这是这个 For 循环 O(N) 的时间复杂度? - Why is this the Time Complexity of this For Loop O(N)? 为什么StringBuilder.append时间复杂度为O(1) - Why StringBuilder.append time complexity is O(1)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM