java - 为什么 java.util.Arrays 使用两种排序算法?

标签 java arrays sorting quicksort comparator

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/

相关文章:

Ruby:从对象数组中的一个值创建新数组

python - Python 中的合并排序 - RuntimeError : maximum recursion depth exceeded

java - 如何从另一个方法访问字符串?

java - Spring security 有时会在成功登录后重定向到默认页面而不是预登录页面

java - 如何读取我的两个数组?

PHP - 从开始和结束时间戳集构建时间线数据的最佳方式

java - 为什么 Arrays.sort(arr) 返回 0 值

Java switch语句默认放置的效率

Java 文件下载器不工作

java - 在 Java 中使用 char 索引访问数组