views:

742

answers:

5

Heap Sort has a worst case complexity is O(nlog) n wnile Quicksort is O(n^2). But emperical evidences say quicksort is superior. Why is that??

+4  A: 

Here's a couple explanations:

http://www.cs.auckland.ac.nz/software/AlgAnim/qsort3.html

http://users.aims.ac.za/~mackay/sorting/sorting.html

Essentially, even though the worst case for quick sort is O(n^2) it on average will perform better. :-)

klabranche
Thumbs up! You beat me to the exact same answer lol
Steve
A: 

Average-case complexity, and the fact that you can take simple steps to minimize the risk of worst-case complexity in Quicksort (e.g. select the pivot as a median of three elements rather than a single selected position).

joel.neely
+6  A: 

One of the major factors is that quicksort has better locality of reference -- the next thing to be accessed is usually close in memory to the thing you just looked at. By contrast, heapsort jumps around significantly more. Since things that are close together will likely be cached together, quicksort tends to be faster.

However, quicksort's worst-case performance is significantly worse than heapsort's is. Because some critical applications will require guarantees of speed performance, heapsort is the right way to go for such cases.

John Feminella
For small working sets the locality of reference issue is critical to avoiding unwanted page faults. It is a strong argument to end the function with a call to sort the left hand most partition, followed by a tail recursive optimization for the right hand partition.
EvilTeach
But not strong enough to do it in practice. Always sort the smallest partition first to avoid blowing the stack
Stephan Eggermont
+2  A: 

Well let's see.. from http://www.sorting-algorithms.com/

Heap Sort (random)

Quick Sort (random)

Jeff Atwood
A: 

The big-O notation means that the time required to sort n items is bounded above by the function c*n*log(n), where c is some unspecified constant factor. There is no reason why the constant c should be the same for quicksort and heapsort. So the real question is: why would you expect them to be equally fast?

Quicksort has always been somewhat faster than heapsort in practice, but the difference has become larger recently since, as mentioned before, locality of memory access has become so important to execution speed.

steven