调整数组顺序使得奇数位于偶数前面

来源:互联网 发布:谁人知 刘德华 编辑:程序博客网 时间:2024/05/17 06:19

使用双指针,一个从头开始,一个从尾部开始,若第一个遇到偶数,且第二个遇到奇数则互换,结束的条件就是指针相遇。

package twoPointer;public class jishuoushi {    private static void change(int[] a) {        if (a.length == 0 || a == null) {            return;        }        int i = 0, j = a.length - 1;        while (i < j) {            while ((a[i] & 0x1) == 1 && i < j) {                i++;            }            while ((a[j] & 0x1) != 1 && i < j) {                j--;            }            if (i < j) {                int tmp = a[i];                a[i] = a[j];                a[j] = a[i];            }        }    }    public static void main(String[] args) {            int [] tes={1,4,2,1,7,3,1,9,6};            change(tes);            for(int i=0;i<tes.length;i++){                System.out.print(tes[i]+"\t");            }    }}
0 0