Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Arrays.sort quicksort and mergesort [duplicate]

Tags:

java

sorting

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!

like image 341
OckhamsRazor Avatar asked Apr 20 '12 18:04

OckhamsRazor


People also ask

How will you sort an array with many duplicated values in Java?

A simple solution would be to use efficient sorting algorithms like Merge Sort, Quicksort, Heapsort, etc., that can solve this problem in O(n. log(n)) time, but those will not take advantage of the fact that there are many duplicated values in the array. A better approach is to use a counting sort.

What is the disadvantage of Mergesort compared to Quicksort?

Additional storage space requirement : Merge sort is not in place because it requires additional memory space to store the auxiliary arrays. The quick sort is in place as it doesn't require any additional storage.

Does merge sort work with duplicates?

To use merge sort to remove duplicates, you would ignore elements that are repeated in the merging process.

Which sorting algorithm is best for identical elements?

3-way QuickSort performs very well when there are large number of duplicates. Save this answer.


1 Answers

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.

like image 149
Eugene Retunsky Avatar answered Nov 15 '22 18:11

Eugene Retunsky