有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
当前回答
对于列表
Collections.sort(list, Collections.reverseOrder());
对于数组
Arrays.sort(array, Collections.reverseOrder());
其他回答
另一种选择可能是(对于数字!!)
将数组乘以-1 排序 再乘以-1
从字面上说:
array = -Arrays.sort(-array)
对于上面的讨论,这里有一个简单的示例,按降序对原始数组进行排序。
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = { 5, 4, 1, 2, 9, 7, 3, 8, 6, 0 };
Arrays.sort(nums);
// reverse the array, just like dumping the array!
// swap(1st, 1st-last) <= 1st: 0, 1st-last: nums.length - 1
// swap(2nd, 2nd-last) <= 2nd: i++, 2nd-last: j--
// swap(3rd, 3rd-last) <= 3rd: i++, 3rd-last: j--
//
for (int i = 0, j = nums.length - 1, tmp; i < j; i++, j--) {
tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
// dump the array (for Java 4/5/6/7/8/9)
for (int i = 0; i < nums.length; i++) {
System.out.println("nums[" + i + "] = " + nums[i]);
}
}
}
输出:
nums[0] = 9
nums[1] = 8
nums[2] = 7
nums[3] = 6
nums[4] = 5
nums[5] = 4
nums[6] = 3
nums[7] = 2
nums[8] = 1
nums[9] = 0
我不知道你的用例是什么,但是除了这里的其他答案之外,另一个(惰性)选项是仍然按照你指出的升序排序,但然后以反向顺序迭代。
你可以使用这个对所有类型的对象进行排序
sort(T[] a, Comparator<? super T> c)
Arrays.sort(a, Collections.reverseOrder());
arrays .sort()不能直接用于按降序对基本数组进行排序。如果试图通过传递Collections.reverseOrder()定义的反向Comparator来调用Arrays.sort()方法,它将抛出错误
没有合适的sort方法(int[],comparator)
这将很好地工作与“对象数组”,如Integer Array,但将不适用于原始数组,如int Array。
按降序对原始数组排序的唯一方法是,首先按升序对数组排序,然后在适当的位置反转数组。这对于二维基元数组也是成立的。
没有显式比较器:
Collections.sort(list, Collections.reverseOrder());
使用显式比较器:
Collections.sort(list, Collections.reverseOrder(new Comparator()));