Java数组按降序排序?

362

有没有简单的方法可以像在Arrays类中升序排序一样降序排序数组?

还是说我必须停止懒惰并自己完成此操作 :[


6
很多以下的解决方案适用于整数类型而不是int类型(确保你使用适当的类型)。 - Manish Jain
29个回答

1

注意:这是一个N log N时间复杂度,但更容易阅读和理解如何进行反向排序。

感谢Ken提出此解决方案的建议。

    // this func sorts in n log n time complexity
    public void sort_reverse(int[] arr) {
        // 1. sort the arr in asc order
        Arrays.sort(arr);
        // 2. now sort all values in descending order
        for (int i = 0, j = arr.length - 1; i < arr.length / 2;i++) {
            int tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
            j--;
        }
    }

0
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的数组,您可以通过更改“返回类型”,“参数类型”和变量“x”的类型来将其用于排序任何其他类型的数组(如int,float等)。您还可以在if条件中将“> =”更改为“< =”以使顺序升序。


0
这对我有用:
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

0

我知道这是一个相当旧的帖子,但这是关于整数和Java 8的更新版:

Arrays.sort(array, (o1, o2) -> o2 - o1);

请注意,对于正常的升序(或Comparator.comparingInt()),它是“o1-o2”。
这也适用于任何其他类型的对象。比如说:
Arrays.sort(array, (o1, o2) -> o2.getValue() - o1.getValue());

5
这仅适用于引用类型数组,而不适用于基本类型数组。 - kimbaudi

0

我有以下可行的解决方案

    public static int[] sortArrayDesc(int[] intArray){
    Arrays.sort(intArray);                      //sort intArray in Asc order
    int[] sortedArray = new int[intArray.length];   //this array will hold the sorted values

    int indexSortedArray = 0;
    for(int i=intArray.length-1 ; i >= 0 ; i--){    //insert to sortedArray in reverse order
        sortedArray[indexSortedArray ++] = intArray [i];
    }
    return sortedArray;
}

0

有一种方法可能会稍微麻烦一些,但它确实有效。 这是一种按降序排序int数组的方法。

希望这能在某一天帮助到某个人:

public static int[] sortArray (int[] array) {
    int [] sortedArray = new int[array.length];
    for (int i = 0; i < sortedArray.length; i++) {
        sortedArray[i] = array[i];
    }
    
    boolean flag = true;
    int temp;
    while (flag) {
        flag = false;
        for (int i = 0; i < sortedArray.length - 1; i++) {
            if(sortedArray[i] < sortedArray[i+1]) {
                temp = sortedArray[i];
                sortedArray[i] = sortedArray[i+1];
                sortedArray[i+1] = temp;
                flag = true;
            }
        }
    }
    
    return sortedArray;
    
}

0

有时候我们通过实例练习是很好的,这里有一个完整的例子:

sortdesc.java

import java.util.Arrays;
import java.util.Collections;
class sortdesc{
public static void main(String[] args){
       // int Array
       Integer[] intArray=new Integer[]{
                 new Integer(15),
                 new Integer(9),
                 new Integer(16),
                 new Integer(2),
                 new Integer(30)};

       // Sorting int Array in descending order
       Arrays.sort(intArray,Collections.reverseOrder());

       // Displaying elements of int Array
       System.out.println("Int Array Elements in reverse order:");
       for(int i=0;i<intArray.length;i++)
          System.out.println(intArray[i]);

       // String Array
       String[] stringArray=new String[]{"FF","PP","AA","OO","DD"};

       // Sorting String Array in descending order
       Arrays.sort(stringArray,Collections.reverseOrder());

       // Displaying elements of String Array
       System.out.println("String Array Elements in reverse order:");
       for(int i=0;i<stringArray.length;i++)
          System.out.println(stringArray[i]);}}

正在编译...

javac sortdec.java

调用它...

java sortdesc

输出

Int Array Elements in reverse order:
30
16
15
9
2
String Array Elements in reverse order:
PP
OO
FF
DD
AA

如果您想尝试一个字母数字数组...
//replace this line:
String[] stringArray=new String[]{"FF","PP","AA","OO","DD"};

//with this:
String[] stringArray=new String[]{"10FF","20AA","50AA"};

你将会得到以下的输出:

50AA
20AA
10FF

源代码


0

使用 Comparator 的另一种方式

import java.util.Arrays;
import java.util.Comparator;
...

Integer[] aInt = {6,2,3,4,1,5,7,8,9,10};
Arrays.sort(aInt, Comparator.reverseOrder()  );

-2

我知道这里有很多答案,但仍然认为,没有人尝试使用核心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.

很愿意向您学习!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接