Java - Ordering array values from highest to lowes

2019-06-14 19:19发布

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

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?

4条回答
Luminary・发光体
2楼-- · 2019-06-14 19:58

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!

查看更多
叼着烟拽天下
3楼-- · 2019-06-14 19:59

Try this:

return Arrays.sort(arr);
查看更多
Explosion°爆炸
4楼-- · 2019-06-14 20:09

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];
        }
    }
查看更多
beautiful°
5楼-- · 2019-06-14 20:18

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.

查看更多
登录 后发表回答