有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
有什么简单的方法来降序排序一个数组,就像他们有一个升序排序在数组类?
还是说我必须停止懒惰,自己做这件事:[
当前回答
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条件中将">="更改为"<="以使顺序上升。
其他回答
你可以使用这个对所有类型的对象进行排序
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。
按降序对原始数组排序的唯一方法是,首先按升序对数组排序,然后在适当的位置反转数组。这对于二维基元数组也是成立的。
我知道这里有很多答案,但仍然认为,没有人尝试使用核心java。 使用集合api,你最终会浪费这么多的内存和残差。
这是一个纯核心概念的尝试,是的,如果你更关心内存占用,这可能是更好的方法。
int[] elements = new int [] {10,999,999,-58,548,145,255,889,1,1,4,5555,0,-1,-52};
//int[] elements = null;
if(elements != null && elements.length >1)
{
int max = 0, index = 0;
for(int i =0;i<elements.length;i++)//find out what is Max
{
if(elements[i] > max)
{
max = elements[i];
index = i;
}
}
elements[index] = elements[0];//Swap the places
elements[0] = max;
for(int i =0;i < elements.length;i++)//loop over element
{
for(int j = i+1;j < elements.length;j++)//loop to compare the elements
{
if(elements[j] > elements[i])
{
max = elements[j];
elements[j] = elements[i];
elements[i] = max;
}
}
}
}//i ended up using three loops and 2 extra variables
System.out.println(Arrays.toString(elements));//if null it will print null
// still love to learn more, please advise if we can do it better.
我也喜欢向你学习!
没有显式比较器:
Collections.sort(list, Collections.reverseOrder());
使用显式比较器:
Collections.sort(list, Collections.reverseOrder(new Comparator()));
对于包含原语元素的数组,如果有org.apache.commons.lang(3)可供处置,则简单的反向数组(排序后)的方法是使用:
ArrayUtils.reverse(array);
我不知道你的用例是什么,但是除了这里的其他答案之外,另一个(惰性)选项是仍然按照你指出的升序排序,但然后以反向顺序迭代。