按降序对基本类型数组进行排序 [英] Sort arrays of primitive types in descending order

查看:36
本文介绍了按降序对基本类型数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个原始类型数组(double).如何按降序对元素进行排序?

I've got a large array of primitive types (double). How do I sort the elements in descending order?

遗憾的是,Java API 不支持使用 Comparator 对原始类型进行排序.

Unfortunately the Java API doesn't support sorting of primitive types with a Comparator.

可能想到的第一种方法是将其转换为对象列表(装箱):

The first approach that probably comes to mind is to convert it to a list of objects (boxing):

double[] array = new double[1048576];    
Arrays.stream(array).boxed().sorted(Collections.reverseOrder())…

但是,对数组中的每个原语进行装箱速度太慢,导致很大的 GC 压力

However, boxing each primitive in the array is too slow and causes a lot of GC pressure!

另一种方法是排序然后反转:

Another approach 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 approach is also 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆