简体   繁体   English

在 while 循环中排序的列表 stl 的时间复杂度

[英]time complexity for list stl with sort in a while loop

What is time complexity for following code :以下代码的时间复杂度是多少:

while(!list.empty()) {
    list.sort();
    a = list.front();
    list.pop_front(); 
    b = list.front();
    list.pop_front();
    /** do something calculations*/
}

Each invocation of list.sort() has O(N log N) complexity 1 .每次调用list.sort()都有 O(N log N) 复杂度1 It might be faster for a sorted list--but then again, it could also be slower (the standard doesn't guarantee anything in either direction for this case).排序列表可能会更快——但话又说回来,它也可能会更慢(对于这种情况,标准不保证任何方向)。 It's typically implemented as a merge sort, which usually isn't affected much (if at all) by pre-existing order.它通常作为合并排序来实现,它通常不会受到预先存在的顺序的太大影响(如果有的话)。

In this case, you're invoking it O(N) times, so your overall complexity is O(N 2 log N).在这种情况下,你调用它 O(N) 次,所以你的整体复杂度是 O(N 2 log N)。

As already noted in the comments, as long as you only remove items from the front of the list, the list will remain sorted, so there's no need to re-sort at each iteration.正如评论中已经指出的那样,只要您只删除列表前面的项目,列表就会保持排序,因此无需在每次迭代时重新排序。

In addition, I'd note that if you're only removing elements from the beginning, you might want to consider using a std::deque instead of std::list .此外,我会注意到,如果您只是从一开始就删除元素,您可能需要考虑使用std::deque而不是std::list Although you'll get the same computational complexity either way, there's a good chance you'll see a substantial improvement in real-life speed moving from a list to a deque .尽管您将获得相同的计算复杂度,但很有可能您会看到现实生活中从listdeque速度显着提高。 You may not be able to substitute a deque for a list in your case (eg, deque doesn't provide the same iterator stability that list does), but in some cases it can be done.在您的情况下,您可能无法用deque替换list (例如, deque不提供与list相同的迭代器稳定性),但在某些情况下可以做到。


  1. In case you care, the precise wording from the standard (§[list.ops]/32) is: " Complexity : Approximately N log N comparisons, where N == size() ."如果您关心,标准 (§[list.ops]/32) 中的准确措辞是:“复杂性:大约N log N 次比较,其中N == size() 。”

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

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