简体   繁体   English

在插入时保持std向量/列表排序,或者对所有进行排序

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

Lets say I have 30000 objects in my vector/list. 假设我的矢量/列表中有30000个对象。 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? 是否更快一次排序(如std :: sort),或者在逐个添加对象时保持向量/列表的排序?

vector/list WILL NOT be modified later. 向量/列表以后不会被修改。

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. 如果在逐个插入元素时保持向量列表排序,则基本上执行插入排序,理论上在最坏的情况下运行O(n ^ 2)。 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. 输入~30000后,最好采用所有输入,然后使用更快的排序算法对其进行排序。

EDIT: As @Veritas pointed out, We can use faster algorithm to search the position for the element (like binary search). 编辑:正如@Veritas指出的那样,我们可以使用更快的算法来搜索元素的位置(如二进制搜索)。 So the whole process will take O(nlg(n)) time. 所以整个过程需要O(nlg(n))时间。 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. 如果我们想要保持数组排序,那么插入元素的最坏情况需要O(n ^ 2)仍然是整体运行时间。

Sorting after input is still by far the better method rather than keeping it sorted after each iteration. 输入之后的排序仍然是更好的方法,而不是在每次迭代后保持排序。

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. 在插入期间保持vector排序将导致二次性能,因为平均而言,对于插入的每个项目,您将不得不向下移动大约一半的向量。 Sorting once at the end would be n log(n) , rather faster. 最后一次排序将是n log(n) ,相当快。

Depending on your needs it's also possible that set or map may be more appropriate. 根据您的需要, setmap也可能更合适。

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

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