简体   繁体   English

while循环内排序的时间复杂度

[英]time complexity of sorting inside while loop

I am trying to understand the time complexity of an algorithm with below pseudo code:我正在尝试使用以下伪代码了解算法的时间复杂度:

let nums has ArrayList of numbers让 nums 有 ArrayList 的数字

sort(nums)
while(nums.size() > 1) {
   // remove two elements
   nums.remove(0);
   nums.remove(0);

   nums.add(some_number);
   sort(nums);
}

sort(nums) is (N)Log(N) . sort(nums)(N)Log(N) nums.remove(0) is O(N) nums.add() is O(1) nums.remove(0)O(N) nums.add()O(1)

Now what is the time complexity for this algorithm.现在这个算法的时间复杂度是多少。

The final complexity is O(n² log n) since you do n times the operation O(n log n) .最终的复杂度是O(n² log n)因为你做了n次操作O(n log n)

Keep in mind that estimating complexity ( O(...) ) is not the same as establishing the total number of operations (usually the time function T(...) is given by total operations), they are two different concepts.请记住,估计复杂度( O(...) )与确定操作总数不同(通常时间 function T(...)由总操作给出),它们是两个不同的概念。 A great introduction could be Analysis of Algorithms一个很好的介绍可能是算法分析

Thus, the O(...) notation is a upper bound but T(...) is the real steps.因此, O(...)表示法是一个上限,但T(...)是实际步骤。

You can try to calculate exactly the T function, or you can go down the upper bound by improving O , but they will always be different functions, as O applies to the worst case of all possible entries.您可以尝试精确计算T function,或者您可以通过改进O降低上限 go ,但它们始终是不同的函数,因为O适用于所有可能条目的最坏情况。

In your code, we unknown T for the sort function, only their upper bound wich is O(n log n) , then:在您的代码中,对于排序 function,我们未知T ,只有它们的上限为O(n log n) ,然后:

T(n) ≤ O(n log n) + T(3) + O((n - 1) log (n - 1)) + T(3) + O((n - 2) log (n - 2) + ...
T(n) ≤ O(n log n) + n T(3) + n O(n log n)
                               ^^^^^^^^^

Here, we cannot define exactly the T for sorting operations on n-1 , n-2 , ... that is the reason for establishing as a higher level O(n log n) for all of them.在这里,我们无法准确定义T用于对n-1n-2 ,...进行排序操作,这就是为所有这些操作建立更高级别O(n log n)的原因。 Then:然后:

T(n) ≤ O(n log n) + n T(3) + n O(n log n)
T(n) ≤ O(n log n) + O(n) + O(n² log n)
T(n) ≤ O(n² log n)

In the second expression, we have a fixed number of upper bounds , in which case the upper bound will be the highest of the upper bounds.在第二个表达式中,我们有固定数量的上界,在这种情况下,上界将是上界的最高值。

(remove, remove and add is T(3) , goto and comparisons are ignored) (删除、删除和添加是T(3) ,忽略goto和比较)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM