为什么Java数组使用两个不同的排序算法对不同类型的?

编程入门 行业动态 更新时间:2024-10-28 12:30:49
本文介绍了为什么Java数组使用两个不同的排序算法对不同类型的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Arrays.java 的排序方法采用快速排序的基本类型数组和对象数组归并排序。我相信,大部分时间快速排序比归并排序速度更快,成本更低的内存。我的实验支持,虽然两种算法为O(n日志(N))。那么,为什么是用于不同类型不同的算法?

Arrays.java's sort method uses quicksort for arrays of primitives and merge sort for arrays of objects. I believe that most of time quicksort is faster than merge sort and costs less memory. My experiments support that, although both algorithms are O(nlog(n)). So why are different algorithms used for different types?

推荐答案

最可能的原因:快速排序是没有的稳定的,即相等的条目可以在排序过程中改变它们的相对位置;除其他事项外,这意味着如果你整理一个已排序的数组,它可能不会保持不变。

The most likely reason: quicksort is not stable, i.e. equal entries can change their relative position during the sort; among other things, this means that if you sort an already sorted array, it may not stay unchanged.

由于原始类型没有身份(没有办法区分两个int具有相同的值),这没有关系他们。但对于引用类型,它可能会导致一些应用程序出现问题。因此,稳定的合并排序用于那些

Since primitive types have no identity (there is no way to distinguish two ints with the same value), this does not matter for them. But for reference types, it could cause problems for some applications. Therefore, a stable merge sort is used for those.

OTOH,理由不使用(保证的n * log(n))的合并排序基本类型可能是因为它需要使阵列的克隆。引用类型,其中提到的对象通常占用比引用的数组得多存储器,这通常并不重要。但对于基本类型,克隆阵列直接加倍的内存使用量。

OTOH, a reason not to use the (guaranteed n*log(n)) merge sort for primitive types might be that it requires making a clone of the array. For reference types, where the referred objects usually take up far more memory than the array of references, this generally does not matter. But for primitive types, cloning the array outright doubles the memory usage.

更多推荐

为什么Java数组使用两个不同的排序算法对不同类型的?

本文发布于:2023-11-29 01:12:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644692.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   不同类型   算法   两个   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!