I recently started using <vector.h>
library and I was wondering, since all the operations are already implemented, IF the method of the sorting algorithm is the most efficient one. Everything runs perfect, there is no doubt, but should I worry about its performance?
If I want to sort up to 6-7 million numbers, should I implement my own sorting method using quick sort?
4 Answers 4
In most libraries, std::sort
is implemented as an introsort, so unless you want to hurt worst-case performance (a lot), you almost certainly do not want to use Quicksort instead. My experience indicates that a home-rolled Quicksort will rarely improve performance noticeably anyway.
The main reason to switch to something else would be to get something like stability (in which case you want std::stable_sort
instead) or ability to work with data that won't fit in RAM (in which case you might want to look into STXXL), not for simple performance.
It's hard to be definitive without knowing your use-case in detail, but as a general rule of thumb;
Don't optimise early
Implement the simplest, most readable and maintainable solution first, and then benchmark it. Often it will be plenty fast enough. You should only start worrying about optimisation when there is a problem, and when you have done enough benchmarking to know where the problem lies.
Sorting algorithms performs different based on your data collection's certain properties.
You say you just started using , so you won't likely to write faster sorting algorithms than people who created C++ and its libraries. Use standard libraries.
It is unlikely you will be able to create a sort faster than std::sort in most cases. its even faster than the C qsort() in many cases.
-
oh really, what about TwoUniqueSort :) critticall.com/sort.html. But yeah... for mainstream, STL is as good as you should need it to be.DXM– DXM2012年05月17日 18:38:18 +00:00Commented May 17, 2012 at 18:38
-
std::sort is faster because the compiler can inline the comparision (rather than using a function pointer), not because of the algorithm used. In C++, it's simple to add that optimization in any algorithm you implement yourself (use a template).user7043– user70432012年05月17日 18:59:03 +00:00Commented May 17, 2012 at 18:59
<vector.h>
! Standard C++ moved to<vector>
back in the late '90s. All of the standard headers now omit the.h
that standard C uses. (In contrast, Boost uses.hpp
, which is what a lot of new C++ code uses outside the standard library.)