有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
当前回答
这里有很多乱七八糟的东西——人们建议非原始值的解决方案,尝试从基础上实现一些排序算法,给出涉及额外库的解决方案,炫耀一些俗套的解决方案等等。最初问题的答案是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}。如果你有一个不是整数的数组——使用相应的对象而不是整数。
其他回答
你可以使用这个对所有类型的对象进行排序
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。
按降序对原始数组排序的唯一方法是,首先按升序对数组排序,然后在适当的位置反转数组。这对于二维基元数组也是成立的。
对于上面的讨论,这里有一个简单的示例,按降序对原始数组进行排序。
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
在这里加上我对几个不同场景的答案 对于数组
Arrays.sort(a, Comparator.reverseOrder());
FWIW列表
Lists.reverse(a);
任何及所有收集
Collections.reverse(a);
这招对我很管用:
package doublearraysort;
import java.util.Arrays;
import java.util.Collections;
public class Gpa {
public static void main(String[] args) {
// initializing unsorted double array
Double[] dArr = new Double[] {
new Double(3.2),
new Double(1.2),
new Double(4.7),
new Double(3.3),
new Double(4.6),
};
// print all the elements available in list
for (double number : dArr) {
System.out.println("GPA = " + number);
}
// sorting the array
Arrays.sort(dArr, Collections.reverseOrder());
// print all the elements available in list again
System.out.println("The sorted GPA Scores are:");
for (double number : dArr) {
System.out.println("GPA = " + number);
}
}
}
输出:
GPA = 3.2
GPA = 1.2
GPA = 4.7
GPA = 3.3
GPA = 4.6
The sorted GPA Scores are:
GPA = 4.7
GPA = 4.6
GPA = 3.3
GPA = 3.2
GPA = 1.2
你可以用这个:
Arrays.sort(data, Collections.reverseOrder());
Collections.reverseOrder()返回一个使用逆自然顺序的比较器。你可以使用Collections.reverseOrder(myComparator)来获得你自己的比较器的反向版本。