Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 885
tower120 Avatar asked Apr 08 '14 19:04

tower120


2 Answers

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.

like image 87
Beowulf Avatar answered Nov 18 '22 21:11

Beowulf


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.

like image 28
Mark B Avatar answered Nov 18 '22 21:11

Mark B