In the Arrays class quick sort is used for sorting primitives but for sorting objects, it's merge sort.
I wonder why this is so?
2 Answers 2
The reason for using mergesort is that they want a stable algorithm - e.g. where equal objects (by compareTo()
or compare()
) are at the same relative order as before.
For primitives, equality implies "non-distinguish-ability". When sorting {5, 3, 5}
to {3, 5, 5}
it does not matter which of the fives was the first one before.
So we can use the quicker (and non-stable) quicksort algorithm here.
Just a guess, but quicksort is O(n^2) in the worst case, while merge sort is stable (guaranteed O(n log n)).
The worst case for quicksort is triggered by equal values.. and equal primitives are identical, while "equal" objects may not be.
-
3stable (guaranteed O(n log n)) - being stable has nothing to do with pessimistic complexity. Stable sorting algorithm keeps the order of items that are considered equal.Tomasz Nurkiewicz– Tomasz Nurkiewicz2011年03月23日 21:07:19 +00:00Commented Mar 23, 2011 at 21:07
-
You're correct. Brain fart, sorry :) However, merge sort returns more predictable execution times than quicksort which can vary from O(n log n) to O(n^2). That is what I meant, I shouldn't go around using the word stable when talking about sort algorithms^^MarcB– MarcB2011年03月23日 21:22:18 +00:00Commented Mar 23, 2011 at 21:22
-
And you've got to carefully craft your input data (though that can be a problem.. quite a fun way for a DDOS) to get anywhere near O(n^2) for quick sort which is usually faster than mergesort, because well constants DO matter. No the reason is just that no efficient quicksort implementation is stable which is a condition for the java library.Voo– Voo2011年03月23日 23:54:24 +00:00Commented Mar 23, 2011 at 23:54
Arrays
clears this.