将数组中所有奇数放在所有偶数的前面

将数组中,所有奇数放在所有偶数的前面

package array_2_3_1;

import java.util.Arrays;

public class Demo_21 {
    public static void main(String[] args) {
        int[] array = {1,2,3,4,5,6,7,8,9};
        Demo_21 demo = new Demo_21();
        demo.modifyOddAndEvenPosition(array);
        System.out.println(Arrays.toString(array));
    }

    public void modifyOddAndEvenPosition(int[] array){
        int oddIndex = 0;
        int evenIndex = array.length - 1;
        while(oddIndex < evenIndex){
            if (array[oddIndex] % 2 != 0){
                oddIndex ++;
            }
            if (array[evenIndex] % 2 == 0){
                evenIndex --;
            }
            //oddIndex < evenIndex防止5,6互换
            if ( (oddIndex < evenIndex) && (array[oddIndex] % 2 == 0) && (array[evenIndex] % 2 != 0)){
                int temp = array[oddIndex];
                array[oddIndex] = array[evenIndex];
                array[evenIndex] = temp;
                oddIndex ++;
                evenIndex --;
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/tmax52HZ/article/details/106614615
今日推荐