按降序对基本类型的数组进行排序 [英] Sort arrays of primitive types in descending order
问题描述
我有一大堆原始类型(双)。
如何按降序对元素进行排序?
I've got a large array of primitive types (double). How do I sort the elements in descending order?
不幸的是,Java API不支持对基本类型进行排序比较器。
Unfortunately the Java API doesn't support sorting of primitive types with a Comparator.
一种解决方法是排序然后反转:
One workaround would be to sort and then reverse:
double[] array = new double[1048576];
...
Arrays.sort(array);
// reverse the array
for (int i = 0; i < array.length / 2; i++) {
// swap the elements
double temp = array[i];
array[i] = array[array.length - (i + 1)];
array[array.length - (i + 1)] = temp;
}
这很慢 - 特别是如果数组已经排序得很好。
This is slow - particularly if the array is already sorted quite well.
什么是更好的选择?
推荐答案
Java Primitive 包括基于自定义比较器对原始数组进行排序的功能。使用它和Java 8,你的样本可以写成:
Java Primitive includes functionality for sorting primitive arrays based on a custom comparator. Using it, and Java 8, your sample could be written as:
double[] array = new double[1048576];
...
Primitive.sort(array, (d1, d2) -> Double.compare(d2, d1), false);
如果您使用的是Maven,可以将其包括在内:
If you're using Maven, you can include it with:
<dependency>
<groupId>net.mintern</groupId>
<artifactId>primitive</artifactId>
<version>1.2.1</version>
</dependency>
当您传递 false
作为第三个参数时到 sort
,它使用不稳定的排序,简单编辑Java的内置双枢轴快速排序。这意味着速度应该接近内置排序的速度。
When you pass false
as the third argument to sort
, it uses an unstable sort, a simple edit of Java's built-in dual-pivot quicksort. This means that the speed should be close to that of built-in sorting.
完全披露:我编写了Java Primitive库。
Full disclosure: I wrote the Java Primitive library.
这篇关于按降序对基本类型的数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!