Java中整数数组排序方法

一、正序排列(从小到大)

方式一:针对普通整数数组

public class IntNums {
    
    
    public static void main(String[] args) {
    
    
        int[] nums = {
    
    1,4,2,3};
        //方式一
        Arrays.sort(nums);
        for(int i = 0; i < nums.length; i++){
    
    
            System.out.println("第i位: " + i + "     元素为" + nums[i]);
        }
    }
}

方式二:针对List类型

public class IntNums {
    
    
    public static void main(String[] args) {
    
    
        List<Integer> array2 = new ArrayList<>();
        array2.add(2);
        array2.add(1);
        array2.add(3);
        array2.add(0);

        Collections.sort(array2);

        for(int j = 0; j < array2.size(); j++){
    
    
            System.out.println("第j位: " + j + "     元素为" + array2.get(j));
        }
    }
}

二、倒序排列(从大到小)

public class IntNums {
    
    
    public static void main(String[] args) {
    
    
        // 倒序排列
        Integer[] array2 = {
    
    2, 5, -2, 6, -3, 8, 0, -7, -9, 4};
        Arrays.sort(array2, new Comparator() {
    
    
           @Override
           public int compare(Object o1, Object o2) {
    
    
                Integer e1 = (Integer)o1;
                Integer e2 = (Integer)o2;

                return e1 > e2 ? -1 : 1;
           }
       });

        for(int j = 0; j < array2.length; j++){
    
    
            System.out.println("第j位: " + j + "     元素为" + array2[j]);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/sinat_34241861/article/details/118895644