本文介绍了java中Collections#sort方法的时间复杂度是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java中集合#sort 方法的时间复杂度是多少?使用了哪种算法?

What is the time complexity of Collections#sort method in java? Which algorithm is used?

Collection#sort 排序 ArrayList的好方法 10 ^ 6?

Is Collection#sort a good method for sorting an ArrayList of 10^6?

推荐答案

这取决于您使用的Java版本。 但最后,Big-O时间复杂度仍为O(N * log(N))。

This depends on the version of Java you use. But in the end, the Big-O time complexity is still O(N*log(N)).

对于Java 6,它是修改后的版本mergesort。请查看此处的说明:

For Java 6, it's a modified version of mergesort. Check the description here: Collections#sort for Java 6

对于Java 7,它改进了: / JDK-6804124rel =noreferrer>增强。请注意,具有O(N)的最佳案例,并且证明比以前的实施更快。

For Java 7, it was improved: Collections#sort for Java 7 due to enhancement. Note that TimSort has a best case of O(N) and proves to be faster than the previous implementation.

实现同样有利于升序和降序在其输入数组中,可以在同一输入数组的不同部分中利用升序和降序。它非常适合合并两个或多个排序数组:简单地连接数组并对结果数组进行排序。

The implementation takes equal advantage of ascending and descending order in its input array, and can take advantage of ascending and descending order in different parts of the same input array. It is well-suited to merging two or more sorted arrays: simply concatenate the arrays and sort the resulting array.

该实现改编自Tim Peters的Python列表排序( )。它使用了Peter McIlroy的乐观排序和信息理论复杂性中的技术,参见第四届年度ACM-SIAM离散算法研讨会论文集,第467-474页,1993年1月。

The implementation was adapted from Tim Peters's list sort for Python ( TimSort). It uses techiques from Peter McIlroy's "Optimistic Sorting and Information Theoretic Complexity", in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.

此实现将指定的列表转储到数组中,对数组进行排序,并迭代列表,从数组中的相应位置重置每个元素。这样可以避免因尝试对链接列表进行排序而导致的n2 log(n)性能。

This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.







从理论上讲,它足以使用。但这让我想知道你为什么要在内存中对数据进行排序。如果数据来自数据库,则使用索引列/字段对其进行排序,否则检查您是否知道将用于排序的字段的某些特征,以及是否可以使用O(N)时间复杂度算法,如或。如果没有其他办法,请使用集合#sort

In theory, it is enough to use. But this makes me wonder why would you have to sort the data in memory. If the data comes from a database, then sort it there using an indexed column/field, otherwise check if you know some characteristics of the field you will use for sorting and if you may use a O(N) time complexity algorithm like Bucket Sort or Radix Sort. When there's no other way, use Collections#sort.

这篇关于java中Collections#sort方法的时间复杂度是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 11:16