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 . 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).
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
. 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
. 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.
N == size()
."
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.