简体   繁体   English

Java:就地排序 ArrayList

[英]Java: sorting an ArrayList in place

In Java's standard library, is there a method that would allow one to sort an ArrayList in place, ie using O(1) extra storage?在 Java 的标准库中,是否有一种方法可以让人们就地对ArrayList进行排序,即使用O(1)额外存储?

Collections.sort(List<T>) does not fulfil this requirement since it Collections.sort(List<T>)不满足这个要求,因为它

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.将指定的列表转储到数组中,对数组进行排序,然后遍历列表,从数组中的相应位置重置每个元素。

If there's nothing in the standard library, what third-party libraries can be used to do this?如果标准库中什么都没有,那么可以使用哪些第三方库来做到这一点?

You can extract the underlying array (eg reflection) and perform a Arrays.sort(array, 0, list.size()) on it.您可以提取底层数组(例如反射)并对其执行 Arrays.sort(array, 0, list.size()) 。

Java 7 does not copy the array in Arrays.sort() before sorting the array. Java 7 在对数组进行排序之前不会复制 Arrays.sort() 中的数组。 In Java 6 it does which means that Collections.sort() in Java 6 actually copies the underlying array TWICE to perform the sort.在 Java 6 中,这意味着 Java 6 中的 Collections.sort() 实际上复制了底层数组 TWICE 来执行排序。

As of Java 8 List interface has default void sort(Comparator<? super E> c) API, using which you can sort an instance in place.从 Java 8 开始, List接口具有默认的void sort(Comparator<? super E> c) API,您可以使用它就地对实例进行排序。

The list must be modifiable, iterable and its elements comparable to each other.该列表必须是可修改的、可迭代的,并且它的元素可以相互比较。

Collections.sort() was made to work with any List implementation, and that's why it's not working in place (merging LinkedList in place is difficult and sacrifices stability). Collections.sort()可以与任何 List 实现一起使用,这就是它无法正常工作的原因(合并 LinkedList 很困难并且会牺牲稳定性)。

If you are really worried about sorting in-place you'll have to roll out your own sort funcion.如果您真的担心就地排序,则必须推出自己的排序功能。 It's not really worth your time unless your List is very long.除非你的 List 很长,否则它真的不值得你花时间。

Arrays.sort(Object[]) does the same mergesort and is called internally by Collections.sort() (at least in openjdk) Arrays.sort(Object[])执行相同的合并排序,并由Collections.sort()内部调用(至少在 openjdk 中)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM