Java - 从高到低对数组值进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13446225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:44:55  来源:igfitidea点击:

Java - Ordering array values from highest to lowest

javaarrayshighest

提问by Muhammad Usman

So I want to go about making a method in Java that sortsout all values from an array into highest to lowest. For example: If I'm given this array:

所以我想在 Java 中创建一个方法,将数组中的所有值排序最高到最低。例如:如果我得到这个数组:

int[] nums = {1254, 4875, 9452, 5412, 6245, 5158, 6215, 8426, 20158};

How would I make a method that prints out all of these numbers from highest to lowest?

我将如何制作一种从最高到最低打印出所有这些数字的方法?

回答by awolfe91

You should begin by sorting the array:

您应该首先对数组进行排序:

Arrays.sort(nums);

This will sort the array in ascending order, so if you just loop backward through the loop, that should do it:

这将按升序对数组进行排序,因此如果您只是通过循环向后循环,则应该这样做:

for(int i=nums.length-1; i>=0; i--){
      System.out.println(nums[i]);
}

Hope that helps!

希望有帮助!

回答by Bohemian

Try this:

试试这个:

return Arrays.sort(arr);

回答by Patricia Shanahan

For the specific case of an array of ints, the best option is probably to sort normally and then copy the array reversing the order. If you had an array of Object references, such as an array of Integer, you would also have the option of supplying a Comparator that reverses the normal comparison.

对于整数数组的特定情况,最好的选择可能是正常排序,然后反转顺序复制数组。如果您有一个 Object 引用数组,例如一个 Integer 数组,您还可以选择提供一个 Comparator 来反转正常比较。

回答by Mik378

Updated: I misread the word "descending".

更新:我误读了“降序”这个词。

Here a solution:

这里有一个解决方案:

    public static void main(String[] args) {
        int[] nums = {1254, 4875, 9452, 5412, 6245, 5158, 6215, 8426, 20158};
        reverseOrder(nums);
        for(int i = 0; i < nums.lenght; i++){
          System.out.println(nums[i]);
        }
    }

    private static void reverseOrder(int[] nums) {
        Arrays.sort(nums);
        int[] reverseSortedNum = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            reverseSortedNum[i] = nums[nums.length - 1 - i];
        }
    }