出鞘之剑指offer-第21题 (调整数组顺序使奇数位于偶数前面)

题目:

输入一个整数数组,实现一个函数调整该数组中数字的顺序使得所有奇数位于数组前半部分,所有偶数位于数组后半部分。 

分析一:

 设两个指针,进行奇偶数交换。

代码一: 

package offer.xzs.twentyone;

public class Demo01 {
    public static void main(String[] args) {
        int[] arr = { 1, 2, 3, 4, 5, 6 };
        int[] sort = sort(arr);
        for (int i = 0; i < sort.length; i++) {
            System.out.println(sort[i]);
        }
    }
    public static int[] sort(int[] array) {
        int left = 0;
        int right = array.length - 1;
        int temp;
        while (left < right) {
            while (left < right && array[right] % 2 == 0) {
                right--;
            }
            while (left < right && array[left] % 2 != 0) {
                left++;
            }
            if (left < right) {
                temp = array[left];
                array[left] = array[right];
                array[right] = temp;
            }
        }
        return array;
    }

}

分析二:

 使用额外的数组。

代码二:

package offer.xzs.twentyone;

public class Demo02 {
    public static void main(String[] args) {
        int[] arr = { 1, 2, 3, 4, 5, 6 };
        int[] sort = sort(arr);
        for (int i = 0; i < sort.length; i++) {
            System.out.println(sort[i]);
        }
    }
    public static int[] sort(int[] array) {
        int count = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[i] % 2 == 1) {
                count++;
            }
        }
        int[] copy = array.clone();
        int index1 = 0;
        int index2 = count;
        for (int i = 0; i < copy.length; i++) {
            if (array[i] % 2 != 0) {
                copy[index1++] = array[i];
            } else {
                copy[index2++] = array[i];
            }
        }
        return copy;
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值