为什么 java.util.Arrays 使用两种排序算法?
Why java.util.Arrays uses Two Sorting Algorithms?
java.util.Arrays 对基本类型(例如 int)使用快速排序(在最新版本中实际上是双枢轴快速排序),对实现 Comparable 或使用 Comparator 的对象使用合并排序。
为什么不同?
为什么不选择一个并将其用于所有情况?
很好的解释here:-
Quicksort is faster in both cases. Mergesort is stable in both cases.
But for primitive types quicksort is stable too! That’s because
primitive types in Java are like elementary particles in quantum
mechanics. You can’t tell the difference between one 7 and another 7.
Their value is all that defines them. Sort the array such [7, 6, 6, 7,
6, 5, 4, 6, 0] into [0, 4, 5, 6, 6, 6, 6, 7, 7]. Not only do you not
care which 6 ended up in which position. It’s a meaningless question.
The array positions don’t hold pointers to the objects. They hold the
actual values of the objects. We might as well say that all the
original values were thrown away and replaced with new ones. Or not.
It just doesn’t matter at all. There is no possible way you can tell
the difference between the output of a stable and unstable sorting
algorithm when all that’s sorted are primitive types. Stability is
irrelevant with primitive types in Java.
我认为是稳定的原因。
基元没有身份,所以不可能区分2个具有相同值的整数。对于引用类型,情况并非如此,这可能会有问题,因为快速排序可能会改变它们的相对位置,这就是为什么使用更稳定的合并排序。
此外,不对基元使用 n*log n 可能是因为它需要一个数组的克隆。对于引用类型,这并不重要,因为它们的对象数组通常比相应的引用数组大。但是,对于基元,克隆使用双倍内存。
java.util.Arrays 对基本类型(例如 int)使用快速排序(在最新版本中实际上是双枢轴快速排序),对实现 Comparable 或使用 Comparator 的对象使用合并排序。 为什么不同? 为什么不选择一个并将其用于所有情况?
很好的解释here:-
Quicksort is faster in both cases. Mergesort is stable in both cases. But for primitive types quicksort is stable too! That’s because primitive types in Java are like elementary particles in quantum mechanics. You can’t tell the difference between one 7 and another 7. Their value is all that defines them. Sort the array such [7, 6, 6, 7, 6, 5, 4, 6, 0] into [0, 4, 5, 6, 6, 6, 6, 7, 7]. Not only do you not care which 6 ended up in which position. It’s a meaningless question. The array positions don’t hold pointers to the objects. They hold the actual values of the objects. We might as well say that all the original values were thrown away and replaced with new ones. Or not. It just doesn’t matter at all. There is no possible way you can tell the difference between the output of a stable and unstable sorting algorithm when all that’s sorted are primitive types. Stability is irrelevant with primitive types in Java.
我认为是稳定的原因。
基元没有身份,所以不可能区分2个具有相同值的整数。对于引用类型,情况并非如此,这可能会有问题,因为快速排序可能会改变它们的相对位置,这就是为什么使用更稳定的合并排序。
此外,不对基元使用 n*log n 可能是因为它需要一个数组的克隆。对于引用类型,这并不重要,因为它们的对象数组通常比相应的引用数组大。但是,对于基元,克隆使用双倍内存。