Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can sort() in C++ have a n^2 performance?

When trying to estimated the performance of a program, I always treated sort() function as a worst-performance-n^2 function. However, I came across a Wikipedia page:

sort(C++)

Which states that the GNU C Library sort() uses some hybrid sorting algorithm called Introsort first, then do insertion sort. The corresponding page to Introsort claims that this algorithm has a worst case performance of nlogn. However, since I am not familiar with this algorithm, I still have the following worries about sort():

1) Can the hybrid algorithm used by GNU sort() guarantee a O(nlogn) performance? If so, how big can the constant overhead of the nlogn be?

2) Are there any other implementations that could cause sort() to perform worse than this (or better, which would be great)?

EDIT: Reply to Kevin: The sort() mentioned is std::sort().

Thanks!

like image 947
zw324 Avatar asked Dec 21 '22 13:12

zw324


1 Answers

The use of quicksort and introsort (which is a variant of the former, with guaranteed O(n log n) performance achieved by switching to heapsort on worst case inputs) in place of other theoretically better algorithms like mergesort is due to the fact that the average case is the same, and the constants much lower (in the constants you can include the fact that it can be sorted in place, so there are no reallocations, and copies). And the worst case is bad, but quite improvable. In general, it is assumed that the performance of sort is O( n log n ).

If you are concerned about the hidden constants, then the question is not theoretical, but rather a question of performance. When trying to optimize you are better off measuring the algorithm on your actual data, analyzing the results of the measurement, and then determining where the time is spent and if it can be improved. But that is a completely different problem from the theoretical one.

like image 162
David Rodríguez - dribeas Avatar answered Jan 04 '23 23:01

David Rodríguez - dribeas