按降序对基本类型数组进行排序

编程入门 行业动态 更新时间:2024-10-11 01:18:48
本文介绍了按降序对基本类型数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个大原始类型数组(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) -> Doublepare(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.

更多推荐

按降序对基本类型数组进行排序

本文发布于:2023-11-11 08:52:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577945.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   类型   降序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!