keep std vector/list sorted while insert, or sort all

三世轮回 提交于 2019-11-29 19:52:36

问题


Lets say I have 30000 objects in my vector/list. Which I add one by one.
I need them sorted.
Is it faster to sort all at once (like std::sort), or keep vector/list sorted while I add object one by one?

vector/list WILL NOT be modified later.


回答1:


When you are keeping your vector list sorted while inserting elements one by one , you are basically performing an insertion sort, that theoretically runs O(n^2) in worst case. The average case is also quadratic, which makes insertion sort impractical for sorting large arrays.

With your input of ~30000 , it will be better to take all inputs and then sort it with a faster sorting algorithm.

EDIT: As @Veritas pointed out, We can use faster algorithm to search the position for the element (like binary search). So the whole process will take O(nlg(n)) time. Though , It may also be pointed that here inserting the elements is also a factor to be taken into account. The worst case for inserting elements takes O(n^2) that is still the overall running time if we want to keep the array sorted.

Sorting after input is still by far the better method rather than keeping it sorted after each iteration.




回答2:


Keeping the vector sorted during insertion would result in quadratic performance since on average you'll have to shift down approximately half the vector for each item inserted. Sorting once at the end would be n log(n), rather faster.

Depending on your needs it's also possible that set or map may be more appropriate.



来源:https://stackoverflow.com/questions/22946772/keep-std-vector-list-sorted-while-insert-or-sort-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!