有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
当前回答
对于上面的讨论,这里有一个简单的示例,按降序对原始数组进行排序。
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
其他回答
另一个解决方案是,如果你正在使用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。
这个解决方案的美妙之处在于(在我看来),它可以用来对用户定义的类进行排序,甚至可以根据特定的属性对它们进行排序。如果可比接口的实现听起来让你望而生畏,我建议你不要这么想,事实并非如此。这个关于如何实现可比性的链接让我的事情变得简单多了。希望人们可以利用这个解决方案,你的快乐甚至可以和我的一样。
你可以使用这个对所有类型的对象进行排序
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。
按降序对原始数组排序的唯一方法是,首先按升序对数组排序,然后在适当的位置反转数组。这对于二维基元数组也是成立的。
int数组降序排序的简单方法:
private static int[] descendingArray(int[] array) {
Arrays.sort(array);
int[] descArray = new int[array.length];
for(int i=0; i<array.length; i++) {
descArray[i] = array[(array.length-1)-i];
}
return descArray;
}
我知道这是一个相当老的线程,但这里是一个更新版本的整数和Java 8:
Arrays.sort(array, (o1, o2) -> o2 - o1);
注意,对于正常的升序(或Comparator.comparingInt()),它是“o1 - o2”。
这也适用于任何其他类型的对象。说:
Arrays.sort(array, (o1, o2) -> o2.getValue() - o1.getValue());
public double[] sortArrayAlgorithm(double[] array) { //sort in descending order
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[i] >= array[j]) {
double x = array[i];
array[i] = array[j];
array[j] = x;
}
}
}
return array;
}
只需使用此方法按降序对double类型的数组进行排序,您可以使用它对任何其他类型的数组(如int, float等)进行排序,只需将“返回类型”,“参数类型”和变量“x”类型更改为相应的类型。您还可以在if条件中将">="更改为"<="以使顺序上升。