给定数组,按先奇后偶顺序排列

第一种

    public static void sort(int[] arr) {
        int length = arr.length;
        for (int i = 0; i < length; i++) {
            for (int j = 0; j < length-1; j++) {
                if (arr[j] % 2 == 0 && arr[j + 1] % 2 == 1) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
    public static void main(String[] args) {
        int [] arr ={3,2,3,5,6,0};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }
}

第二种

public static int[] oddSwap(int[] arr){
    int[] brr = new int[arr.length];
    int oldArrIndex=0,
            newBrrPIndex=0,
            newBrrLIndex = brr.length-1;
    for(;oldArrIndex < arr.length;oldArrIndex++){
        if(arr[oldArrIndex] % 2 == 0){//偶数
            brr[newBrrLIndex--] = arr[oldArrIndex];
        }else{
            brr[newBrrPIndex++] = arr[oldArrIndex];
        }
    }
    return brr;
}
public static void main(String[] args) {
    int[] arr = {3,2,3,5,6,0};
    arr = oddSwap(arr);
    System.out.println(Arrays.toString(arr));
}
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44827160/article/details/88925307