为什么归并排序是用于Android的/ Java的API对象?对象、Android、Java、API

2023-09-06 15:53:43 作者:游戏VIP贵族

在Java中的 Arrays.sort()对基本类型使用快速排序。另一方面 Arrays.sort()的对象使用合并排序。而且,同样适用 Col​​lection.sort()也使用合并排序。集合排序使用数组类型的实现下面。所以,简单意义上我可以说,原语使用快速排序排序,但对象是使用合并排序排序。

In Java Arrays.sort() for primitive type uses quick sort. On the other hand Arrays.sort() for objects uses Merge sort. And, same goes for Collection.sort() which also uses Merge sort. Collections sort uses Arrays sort implementation underneath. So, in simple sense i can say that primitives are sorted using quick sort but objects are sorted using Merge sort.

我的猜测是它是与排序算法,它的自我。上有快速排序VS归并排序的那么那么多的讨论,如这和< A HREF =htt​​p://stackoverflow.com/questions/70402/why-is-quicksort-better-than-mergesort>这个。似乎是有冲突的要求上哪一个更好,这是可以理解的,因为这取决于数据集。

My guess is it has something to do with sorting algorithm it self. There are so many discussion on SO on Quick sort vs Merge sort, like this and this. Seems to be there are conflicting claims on which one is better, which is understandable as this depend on data sets.

我的理解是

在的地方:快速排序获胜。合并排序可以就地实现为链表 在外部存储器中的数据:归并排序胜 在排序列表(由任何形式的链接列表支持):合并排序获胜。 Link

Android的API似乎遵循相同模式的Java。这是我发现的 Arrays.java

Android API seems to follow the same pattern as Java. This is what i found in Arrays.java

    public static void sort(long[] array) {
    DualPivotQuicksort.sort(array);
}

而这一点,

public static void sort(Object[] array) {
    ComparableTimSort.sort(array);
}

我不明白的是,是什么使合并排序一个很好的候选人进行排序Java或在Android中的对象?为什么不离开这个决定高达开发商?

What i do not understand is, what makes Merge sort a good candidate for sorting objects in Java or in Android? Why not leaving this decision upto developers?

推荐答案

问题的关键是那种稳定 - 如果两个元素是从视图的排序顺序点相等,难道他们出现在结果中的顺序相同在输入

The key issue is sort stability - if two elements are equal from the point of view of the sort order, do they appear in the result in the same order as in the input.

没关系的如 3 中输入的所有实例将被组合在一起,根本没人关心哪个是哪个。

It does not matter for e.g. long. All instances of 3 in the input will be grouped together, and nobody cares which was which.

在另一方面,对象可能不同,因为不影响排序顺序的方式。如果您是通过腿的数量排序的动物,你可能不在乎是否猫和狗留在原来的顺序或没有。

On the other hand, objects may differ in ways that do not affect the sort order. If you are sorting animals by number of legs, you may care whether "cat" and "dog" stay in the original order or not.

的 Arrays.sort 归并排序是稳定的。用于基元的快速排序并不需要是稳定的。

The Arrays.sort mergesort is stable. The quicksort used for the primitives does not need to be stable.