数组中奇数和偶数重新排列,奇数排在前面

这篇博客介绍了一个Java程序,该程序实现了一个功能:在原地且使用O(1)额外空间的情况下,将一个整数数组中的所有奇数移到偶数前面,同时保持奇数和偶数内部的相对顺序不变。代码通过双指针和交换元素来达到目标。
摘要由CSDN通过智能技术生成

- 有个整数数组 ,里面有奇数和偶数,1)将所有奇数挪到偶数前面,2)保障所有奇数和偶数内部相对顺序不发生变化,3)在原数组上操作o(1)的空间复杂度

public class Array {
    public static void main(String[] args) {
        int[] arr = {1, 2, 4, 8, 9, 6};
        int[] ints = orderArray(arr);
        System.out.println(Arrays.toString(ints));
    }

    public static int[] orderArray(int[] array) {
        int count = 0;
        int len = array.length - 1;
        for (int i = 0; i <= len; i++) {
            if (array[i] % 2 == 1) {
                int j = i;
                while (j > count) {
                    int temp = array[j];
                    array[j] = array[j - 1];
                    array[j - 1] = temp;
                    j--;
                }
                count++;
            }
        }
        return array;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值