Stable sorting maintains the relative order of elements that have the same key. For example, imagine that your data set contains records with an employee ID and name. Initial order:
1, Jim 2, George 3, Jim 4, Sally 5, George
You want to sort by name. Stable sorting will arrange items in the following order:
2, George 5, George 1, Jim 3, Jim 4, Sally
Note that duplicate entries for George are in the same relative order as in the original list. Same thing with two Jim records.
Unstable sorting can arrange items as follows:
5, George 2, George 1, Jim 3, Jim 4, Sally
Heapsort is unstable because heap operations can change the relative order of equal elements. Not all Quicksort implementations are stable. It depends on how you implement the separation.
Even though Heapsort has worse O(n log(n)) complexity, this does not tell the whole story. In a real implementation, there are constant factors that theoretical analysis does not take into account. In the case of Heapsort vs. Quicksort finds out that there are ways (like median 5) to make the worst cases of Quicksort very rare. In addition, saving heaps is not free.
Given an array with a normal distribution, Quicksort and Heapsort will work in O(n log(n)) . But Quicksort will run faster because its constant factors are less than the constant factors for Heapsort. Simply put, splitting is faster than saving the heap.
Jim Mischel Nov 29 '11 at 2:09 p.m. 2011-11-29 14:09
source share