Sort an array in Java

后端 未结 17 1252
傲寒
傲寒 2020-11-22 04:53

I\'m trying to make a program that consists of an array of 10 integers which all has a random value, so far so good.

However, now I need to sort them in order from l

17条回答
  •  忘掉有多难
    2020-11-22 05:35

    See below, it will give you sorted ascending and descending both

    import java.util.Arrays;
    import java.util.Collections;
    
    public class SortTestArray {
    
    /**
     * Example method for sorting an Integer array
     * in reverse & normal order.
     */
    public void sortIntArrayReverseOrder() {
    
        Integer[] arrayToSort = new Integer[] {
            new Integer(48),
            new Integer(5),
            new Integer(89),
            new Integer(80),
            new Integer(81),
            new Integer(23),
            new Integer(45),
            new Integer(16),
            new Integer(2)
        };
    
        System.out.print("General Order is    : ");
    
        for (Integer i : arrayToSort) {
            System.out.print(i.intValue() + " ");
        }
    
    
        Arrays.sort(arrayToSort);
    
        System.out.print("\n\nAscending Order is  : ");
    
        for (Integer i : arrayToSort) {
            System.out.print(i.intValue() + " ");
        }
    
    
        Arrays.sort(arrayToSort, Collections.reverseOrder());
        System.out.print("\n\nDescinding Order is : ");
        for (Integer i : arrayToSort) {
            System.out.print(i.intValue() + " ");
        }
    
    }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SortTestArray SortTestArray = new SortTestArray();
        SortTestArray.sortIntArrayReverseOrder();
    }}
    

    Output will be

    General Order is    : 48 5 89 80 81 23 45 16 2 
    
    Ascending Order is  : 2 5 16 23 45 48 80 81 89 
    
    Descinding Order is : 89 81 80 48 45 23 16 5 2 
    

    Note: You can use Math.ranodm instead of adding manual numbers. Let me know if I need to change the code...

    Good Luck... Cheers!!!

提交回复
热议问题