Does std::sort check if a vector is already sorted?

后端 未结 7 1887
难免孤独
难免孤独 2020-12-23 16:50

I believe that the C++ standard for std::sort does not guarantee O(n) performance on a list that\'s already sorted. But still, I\'m wondering whether to your knowledge any i

相关标签:
7条回答
  • 2020-12-23 17:08

    There's no guarantee that it'll check this. Some implementations will do it , others probably won't.

    However, if you suspect that your input might already be sorted (or nearly sorted), std::stable_sort might be a better option.

    0 讨论(0)
  • 2020-12-23 17:10

    The standard sanctions only std::sort implementations with complexity O(n log n):

    Complexity: Approximately N log N (where N == last - first) comparisons on the average.

    See section 25.3.1.1 Sorting [lib.sort] (ISO/IEC 14882:2003(E)).

    Thus, the set of allowed sorting functions is limited, and you are right that it does not guarantee linear complexity.

    Ideal behavior for a sort is O(n), but this is not possible in the average case.

    Of course the average case is not necessarily the exact case you have right now, so for corner cases, there's not much of a guarantee.

    0 讨论(0)
  • 2020-12-23 17:12

    No. Also, it's not logical to have is_sorted() called for any STL implementation. Since, is_sorted() is available already as a stand-alone. And many users may not want to waste execution cycles unnecessarily to call that function when they already know that their container is not sorted.

    STL also should be following the C++ philosophy: "pay per use".

    0 讨论(0)
  • 2020-12-23 17:18

    I suggest you read this comparison of sorting algorithms, it is very well done and informative, it compares a number of sorting algorithms with each other and with GCC's implementation of std::sort. You will notice, in the charts on the given link, that the performance of std::sort for "almost sorted" and "almost reverse" are linear in the number of elements to sort, that is, O(n). So, no guarantee, but you can easily expect that an almost sorted list will be sorted in almost linear-time. But, of course, it does not do a is_sorted check, and even if it will sort a sorted array in linear-time, it won't be as fast as doing a is_sorted check and skipping the sorting altogether. It is your decision to determine if it is better to check before sorting or not.

    0 讨论(0)
  • 2020-12-23 17:19

    Wow! Did you have optimizations all the way cranked up?

    Here's the results of your code on my platform (note the values on the vertical axis).

    0 讨论(0)
  • 2020-12-23 17:19

    And why would any implementation do that check? What would it gain? -- Nothing in average. A good design rule is not to clutter implementation with optimizations for corner cases which make no difference in average. This example is similar to check for self-assignment. A simple answer: don't do it.

    0 讨论(0)
提交回复
热议问题