[英]Sorting an int array from highest to lowest
So I just learned about the Arrays.sort(arrayName);
所以我刚刚了解了
Arrays.sort(arrayName);
and applied it in a project of mine but I found it sorts from lowest to highest. 并将其应用于我的一个项目,但我发现它从最低到最高。 Is there anyway to have it do the opposite?
反正有没有相反的做法? (I don't think I need to post the code in question but if it is needed I'll post it).
(我认为我不需要发布有问题的代码,但如果需要,我会发布它)。
If you use an Integer[]
instead of int[]
, then you can pass a Comparator
as 2nd argument to the sort method. 如果使用
Integer[]
而不是int[]
,则可以将Comparator
作为第二个参数传递给sort方法。 To impose reverse ordering, you can make use of Collections.reverseOrder()
method: 要强制反向排序,可以使用
Collections.reverseOrder()
方法:
Arrays.sort(arr, Collections.reverseOrder());
If you have an int[]
array, you can sort it using Arrays.sort
and then reverse it : 如果你有一个
int[]
数组,你可以使用Arrays.sort
对它进行Arrays.sort
,然后反转它:
int [] tab2 = new int[]{1,5,0,-2};
Arrays.sort(tab2);
ArrayUtils.reverse(tab2);
System.out.print(Arrays.toString(tab2));
Output : 输出:
[5, 1, 0, -2]
Code
of the reverse method (from org.apache.commons.lang.ArrayUtils.reverse(int[])
) : 反向方法的
Code
(来自org.apache.commons.lang.ArrayUtils.reverse(int[])
):
public static void reverse(int[] array) {
if (array == null) {
return;
}
int i = 0;
int j = array.length - 1;
int tmp;
while (j > i) {
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
j--;
i++;
}
}
For some usecases you may come along by just treating your sorted array as "reverse sorted". 对于某些用例,您可以将排序后的数组视为“反向排序”。 Eg to iterate from highest to lowest number you may use
例如,您可以使用从最高到最低的数字迭代
int[] foo = ...;
Arrays.sort(foo);
for (int i=foo.length-1; i>=0; i--) {
doSomethingWith(foo[i]);
}
Integer[]
instead of int[]
Integer[]
而不是int[]
Collections.reverseOrder()
: Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface Collections.reverseOrder()
:返回一个比较器,它对实现Comparable接口的对象集合施加自然顺序的反转 If possible use ArrayList<Integer>
and Collections.sort(list, Collections.reverseOrder())
for stronger case. 如果可能的话,使用
ArrayList<Integer>
和Collections.sort(list, Collections.reverseOrder())
来获得更强的案例。
Integer[] intArr = new Integer[10]; // add some integer Arrays.sort(intArr, Collections.reverseOrder())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.