Java - Ordering array values from highest to lowest [closed]

半腔热情 提交于 2019-12-08 14:14:45

问题


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.



来源:https://stackoverflow.com/questions/13446225/java-ordering-array-values-from-highest-to-lowest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!