简体   繁体   English

如何有效地对int数组进行排序

[英]How to sort int array efficiently

I have array of ints 我有一些整数

int array[] = ...

and I can sort it using 我可以使用它来排序

Arrays.sort(array);

but Arrays.sort uses quicksort, which sometimes result in O(n^2) complexity. 但Arrays.sort使用quicksort,有时会导致O(n ^ 2)复杂度。 I had an idea to convert it to List and then sort it (mergesort is used, so upper bound is O(n log n)) , but the drawback is that it creates a lot of objects due to boxing from int to Integer. 我有一个想法将它转换为List然后对它进行排序(使用mergesort,因此上限是O(n log n)) ,但缺点是由于从int到Integer的装箱,它会创建很多对象。

My third approach is this : 我的第三种方法是:

array = Arrays.stream(array).sorted().toArray();

I operate only on IntStream, but unfortunately the complexity isn't mentioned in the documentation. 我只在IntStream上运行,但不幸的是文档中没有提到复杂性。

I was looking for similar questions and I have found only this Big-O complexity of java.util.stream.Stream<T>.sorted() which isn't helpful at all, because there are two different answers (first is of course partially wrong, because Arrays.sort isn't always O(n log n)) . 我正在寻找类似的问题,我发现只有java.util.stream.Stream <T> .sorted()的Big-O复杂性,这根本没有用,因为有两个不同的答案(首先当然是部分错误,因为Arrays.sort并不总是O(n log n)) What about the second one ? 那第二个怎么样? I haven't found the proof. 我还没有找到证据。

You should investigate Heapsort , while slightly slower it guarantees O(n Log n). 您应该调查Heapsort ,稍微慢一点它保证O(n Log n)。 Quicksort vs heapsort Quicksort vs heapsort

There is also the textbook explanation here . 还有教科书的解释在这里

If the range of integers is small you can use Counting Sort , which uses numbers as array-indexes and, unlike comparison-sort algorithms that have a lower bound of O( nlogn ) (eg Quicksort or Mergesort), it has a complexity of O( n+k ), where k is the range between your min and max value. 如果整数范围很小,你可以使用Counting Sort ,它使用数字作为数组索引,而不像具有O( nlogn )下限的比较排序算法(例如Quicksort或Mergesort),它的复杂度为O ( n + k ),其中k是最小值和最大值之间的范围。

Which algorithm to choose always depends on any extra knowledge you may have regarding the distribution of the array elements. 选择哪种算法总是取决于您对阵列元素分布的任何额外知识。

Just implement the mergesort yourself, it's no rocket science. 只是自己实现mergesort,这不是火箭科学。 After you have implemented it, do take a little time to run some benchmarks and compare the performance of you implementation with that of Arrays.sort . 实现之后,请花一点时间运行一些基准测试,并将实现的性能与Arrays.sort的性能进行比较。 There may be some surprises waiting for you there. 那里可能会有一些惊喜等着你。

Also, read up on premature optimization , I think you might find the notion useful. 另外,阅读过早优化 ,我想你可能会发现这个概念很有用。

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

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