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

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

我有一大堆原始类型(双)。 如何按降序对元素进行排序?

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

发布评论

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

>www.elefans.com

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