Java 按降序排列数组?
我看过比较器和算法,但我对它们没有太多的理解。来自java.util.Collections的比较器。 所以我选择使用:Java 按降序排列数组?,java,arrays,loops,assign,Java,Arrays,Loops,Assign,我看过比较器和算法,但我对它们没有太多的理解。来自java.util.Collections的比较器。 所以我选择使用: //return an array in descending order, using set algorithm public int[] descendSort() { int[] tempArray = new int[temps.length]; for (int i = temps.length-1; i <=
//return an array in descending order, using set algorithm
public int[] descendSort()
{
int[] tempArray = new int[temps.length];
for (int i = temps.length-1; i <= 0; --i)
{
tempArray[i] = temps[i];
}
return tempArray;
}
我的输出结果如下:
The temperatures in descending order is: 0 0 0 0 0 0 0 0 0 0
为什么???条件
i条件i你如何排序,你只是从一个数组复制到另一个数组。下面是使用选择排序的排序代码。
公共int[]descsort(){
for(inti=0,imax)//如果有较大的元素,请跟踪它
int指数=j
int temp=temps[max];
temps[max]=temps[index];
temps[index]=temp;
}
return temps;
}
你是如何排序的,你只是从一个数组复制到另一个数组。
公共int[]descsort(){
for(inti=0,imax)//如果有较大的元素,请跟踪它
int指数=j
int temp=temps[max];
temps[max]=temps[index];
temps[index]=temp;
}
return temps;
}
一行程序(不适用于基本体):
一行程序(不适用于基本体):
按降序排列整数数组的方法如下:
比较器比较器=新比较器(){
按降序排列整数数组的方法如下:
比较器比较器=新比较器(){
我得到了一个越界数组exceptiontempArray[temps.length-I]到tempArray[temps.length-1-I]我得到了一个越界数组exceptiontempArray[temps.length-I]到tempArray[temps.length-1-I]在这里,您可以看到如何使用比较器接口:@hovercraftfullofels我创建了一个方法,在该方法中它对数组进行了排序,所以这不是问题。在这里,您可以看到如何使用比较器接口:@hovercraftfullofels我创建了一个方法,在该方法中它对数组进行了排序,所以这不是问题。
for (int i = 0; i < temps.length; ++i)
{
tempArray[temps.length-1-i] = temps[i];
}
int temp=temps[max];
temps[max]=temps[index];
temps[index]=temp;
}
return temps;
}
Integer[] temps1 = new Integer[] { 45, 76, 12, 102, 107, 65, 43, 67, 81, 14 };
Arrays.sort(temps1, Collections.reverseOrder());
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
};
Integer[] array = new Integer[] { 9,1, 0, 7, 0, 0, 0, 5, 0 };
Arrays.sort(array, comparator);
System.out.println(Arrays.toString(array));