为什么使用两种不同的算法来排序数组?

时间:2021-12-24 14:23:29

In the Arrays class quick sort is used for sorting primitives but for sorting objects, it's merge sort.

在Arrays类中,快速排序用于排序基元,但是对于排序对象,它是合并排序。

I wonder why this is so?

我想知道为什么会这样?

2 个解决方案

#1


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.

使用mergesort的原因是他们想要一个稳定的算法 - 例如其中相等的对象(通过compareTo()或compare())与之前的相对顺序相同。

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.

对于原始人来说,平等意味着“不区分能力”。当将{5,3,5}分类到{3,5,5}时,五个中的哪个是之前的第一个并不重要。所以我们可以在这里使用更快(和非稳定)的快速排序算法。

#2


1  

Just a guess, but quicksort is O(n^2) in the worst case, while merge sort is stable (guaranteed O(n log n)).

只是一个猜测,但在最坏的情况下,快速排序是O(n ^ 2),而合并排序是稳定的(保证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.

快速排序的最坏情况是由相等的值触发..并且相等的基元是相同的,而“相等”的对象可能不是。

#1


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.

使用mergesort的原因是他们想要一个稳定的算法 - 例如其中相等的对象(通过compareTo()或compare())与之前的相对顺序相同。

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.

对于原始人来说,平等意味着“不区分能力”。当将{5,3,5}分类到{3,5,5}时,五个中的哪个是之前的第一个并不重要。所以我们可以在这里使用更快(和非稳定)的快速排序算法。

#2


1  

Just a guess, but quicksort is O(n^2) in the worst case, while merge sort is stable (guaranteed O(n log n)).

只是一个猜测,但在最坏的情况下,快速排序是O(n ^ 2),而合并排序是稳定的(保证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.

快速排序的最坏情况是由相等的值触发..并且相等的基元是相同的,而“相等”的对象可能不是。