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

15,070

Solution 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.

Solution 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.

Share:
15,070
tower120
Author by

tower120

Updated on June 04, 2022

Comments

  • tower120
    tower120 almost 2 years

    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.