10

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?

Paul Sasik
81.8k23 gold badges152 silver badges191 bronze badges
asked Mar 23, 2011 at 20:50
4
  • 2
    Can you provide a link to what Java implementation you're talking about? This is not mandated by the JLS. Commented Mar 23, 2011 at 20:52
  • @templatetypedef it's not mandated, but is "an implementation note", and is the case in sun's implementation. The javadoc of Arrays clears this. Commented Mar 23, 2011 at 20:57
  • possible duplicate of Why does java.util.Arrays.sort(Object[]) use 2 kinds of sorting algorithms? Commented Mar 23, 2011 at 20:58
  • @Bozho- I agree... My question was mainly whether this was in Sun's implementation, or the OpenJDK, etc. so I could pull up the source myself. Commented Mar 23, 2011 at 20:59

2 Answers 2

14

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.

answered Mar 23, 2011 at 21:24
1

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.

answered Mar 23, 2011 at 20:55
3
  • 3
    stable (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. Commented 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^^ Commented 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. Commented Mar 23, 2011 at 23:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.