12

Possible Duplicate:
Why java Arrays use two different sort algorithms for different types?

So I was reading the Arrays doc on the various sort implementations. What I noticed was that some of the implementations used a tuned quicksort while others used a modified mergesort. Why the discrepancy?

Thanks!

Community
  • 1
  • 1
OckhamsRazor
  • 4,824
  • 13
  • 51
  • 88

1 Answers1

26

Quicksort is used for arrays of primitive types while mergesort for Object[] arrays.

The main reason why mergesort is used for Objects that mergesort is stable - it does not reorder elements that are equal: http://en.wikipedia.org/wiki/Sorting_algorithm#Stability

For primitives the stability of the sort is meaningless, as you cannot distinguish two values that are equal. Hence, quicksort is used (except when sorting an array of Objects, for which mergesort is performed). Moreover, quicksort can be done in place, so there is no need to allocate another array.

Eugene Retunsky
  • 13,009
  • 4
  • 52
  • 55