Reputation: 63
In Java Heap sort seems a best sorting algorithm while sorting an array of random numbers according to http://www.sorting-algorithms.com/ But still I read that Heap sort is not stable, why so? Which sorting algorithm should be considered best algorithm while sorting an array or random numbers?
Upvotes: 1
Views: 6020
Reputation: 8292
Stable Sort: A sort which doesn't change the relative position of same/equal elements.
For example,
I/P: 2, 4, 3(a), 5, 1, 3(b)
O/P: 1, 2, 3(a), 3(b), 4, 5In I/P 3(b) comes after 3(a) and the same stays intact in the O/P.
It can be explained very easily. Let us take the following example:
3,3,2,1
Consider the first 3 to be 3(a) and second 3 to be 3(b).
3(a),3(b),2,1
Heapsort begins by extracting the maximum number from the max-heap, which is the first element and then putting it on the last position.
3(b),2,1,3(a)
Then size is decreased by 1 and a heapify operation is applied.Therefore the new size is 3 and the first three elements already satisfy the heap property.
Now comes the step which show that heapsort is not stable.
Again we will extract the maximum from the heap which is the first element and put it in last position.
But because size is now 3, the last position is left of 3(a) and hence we get:
2,1,3(b),3(a)
As we can see that order of the elements 3(a) and 3(b) is reversed from the original order and remaining part of the heapsort will only sort the first two elements and therefore, the elements 3(a) and 3(b) will remain intact at their positions. This is the reason that heapsort is not stable.
The final result is
1,2,3(b),3(a)
Upvotes: 2
Reputation: 10560
Because it does not guarantee that when it encounters 2 equal elements in the collection that is being sorted, that their position will be preserved.
Let's say this collection: 3 2 2 1
. When this algorithm will encounter 2 and compare it with 2, it may reverse them.
Sorting algorithms stability.
By the way, in case you don't care about the order of identical items in your collection, then you may chose the fastest one.
Upvotes: 2