剑指offer_14(调整数组顺序使得奇数位于偶数前面)

题意:调整数组顺序使得奇数位于偶数前面
思路:搞两个指针一前一后
代码:

package MianShiTi_14;

public class MianShiTi_14 {

    //将奇数都移到前面,偶数都移到后面
    public static void EvenExchangeOdd(int[] num) throws Exception {
        if(num == null || num.length <= 0){
            throw new Exception("invalid array");
        }
        int begin = 0;
        int end = num.length - 1;
        while (begin < end) {
            while (begin < end && (num[begin]& 0x1) !=0){
                begin++;}
            while (begin < end && (num[end] & 0x1) == 0){
                end--;}
            if(begin < end){
            int tmp = num[begin];
            num[begin] = num[end];
            num[end] = tmp;
            }
        }
    }

    //将能被3整数的都移到后面,不能被3整除的移到前面。
    public static void test3(int[] num) throws Exception {
        if(num == null || num.length <= 0){
            throw new Exception("invalid array");
        }
        int begin = 0;
        int end = num.length - 1;
        while (begin < end) {
            while (begin < end && !is3dividedable(num[begin])){
                begin++;}
            while (begin < end && is3dividedable(num[end])){
                end--;}
            if(begin < end){
            int tmp = num[begin];
            num[begin] = num[end];
            num[end] = tmp;
            }
        }
    }

    public static boolean is3dividedable(int number) {
        return (number % 3 == 0)?true:false;
    }

    public static void prinrArray(int[] number) {
        for (int i : number) {
            System.out.print(i+" ");
        }
    }

    public static void main(String[] args) throws Exception {
        int[] num = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        EvenExchangeOdd(num);
        prinrArray(num);
        System.out.println();
        test3(num);
        prinrArray(num);
    }
}   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值