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.
关于java - 为什么 java.util.Arrays 使用两种排序算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33606078/