Java - Ordering array values from highest to lowes

2019-06-14 19:53发布

问题:

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?

回答1:

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!



回答2:

Try this:

return Arrays.sort(arr);


回答3:

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];
        }
    }


回答4:

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.