有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
当前回答
首先,你需要使用以下命令对数组进行排序:
Collections.sort(myArray);
然后你需要使用以下命令将升序颠倒为降序:
Collections.reverse(myArray);
其他回答
这是我如何排序一个基本类型int数组。
int[] intArr = new int[] {9,4,1,7};
Arrays.sort(nums);
Collections.reverse(Arrays.asList(nums));
结果:
[1, 4, 7, 9]
另一个解决方案是,如果你正在使用Comparable接口,你可以切换你在compareTo(Object bcomparable)中指定的输出值。
例如:
public int compareTo(freq arg0)
{
int ret=0;
if(this.magnitude>arg0.magnitude)
ret= 1;
else if (this.magnitude==arg0.magnitude)
ret= 0;
else if (this.magnitude<arg0.magnitude)
ret= -1;
return ret;
}
在我的程序中,量级是一个具有双数据类型的属性。这是对我定义的类频率按大小的倒序排序。因此,为了纠正这一点,您可以切换<和>返回的值。这将为您提供以下内容:
public int compareTo(freq arg0)
{
int ret=0;
if(this.magnitude>arg0.magnitude)
ret= -1;
else if (this.magnitude==arg0.magnitude)
ret= 0;
else if (this.magnitude<arg0.magnitude)
ret= 1;
return ret;
}
为了使用这个compareTo,我们简单地调用Arrays.sort(mFreq),它会给你排序的数组freq [] mFreq。
这个解决方案的美妙之处在于(在我看来),它可以用来对用户定义的类进行排序,甚至可以根据特定的属性对它们进行排序。如果可比接口的实现听起来让你望而生畏,我建议你不要这么想,事实并非如此。这个关于如何实现可比性的链接让我的事情变得简单多了。希望人们可以利用这个解决方案,你的快乐甚至可以和我的一样。
对于按降序排序的2D数组,只需翻转参数的位置
int[][] array= {
{1, 5},
{13, 1},
{12, 100},
{12, 85}
};
Arrays.sort(array, (a, b) -> Integer.compare(a[1], b[1])); // for ascending order
Arrays.sort(array, (b, a) -> Integer.compare(a[1], b[1])); // for descending order
降序输出
12, 100
12, 85
1, 5
13, 1
Java 8:
Arrays.sort(list, comparator.reversed());
更新: Reversed()反转指定的比较器。通常比较器的顺序是升序的,所以这将顺序改为降序。
这里有很多乱七八糟的东西——人们建议非原始值的解决方案,尝试从基础上实现一些排序算法,给出涉及额外库的解决方案,炫耀一些俗套的解决方案等等。最初问题的答案是50/50。对于那些只想复制/粘贴的人:
// our initial int[] array containing primitives
int[] arrOfPrimitives = new int[]{1,2,3,4,5,6};
// we have to convert it into array of Objects, using java's boxing
Integer[] arrOfObjects = new Integer[arrOfPrimitives.length];
for (int i = 0; i < arrOfPrimitives.length; i++)
arrOfObjects[i] = new Integer(arrOfPrimitives[i]);
// now when we have an array of Objects we can use that nice built-in method
Arrays.sort(arrOfObjects, Collections.reverseOrder());
arrOfObjects现在是{6,5,4,3,2,1}。如果你有一个不是整数的数组——使用相应的对象而不是整数。