Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use two different algorithm for sorting arrays?

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?

like image 730
user590444 Avatar asked Mar 23 '11 20:03

user590444


2 Answers

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.

like image 64
Paŭlo Ebermann Avatar answered Oct 18 '22 09:10

Paŭlo Ebermann


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.

like image 34
MarcB Avatar answered Oct 18 '22 09:10

MarcB