2021-01-21

给定一组数组,奇数位于数组前面,偶数位位于数组后面

方法有两种
方法一
我们先对原来数组遍历一遍,给一个count,记录偶数的个数;然后我们在创建一个新的数组,再遍历一遍,把奇数放在这个新的数组前面,偶数放在新数组后面,最后新的数组赋值给原来的数组,就完成了奇偶的排序。

public class jioushuzu {
    public static void main(String[] args){
        int [] array={1,2,3,4,5,6,7,8};
        int length=array.length;
        int count=0;
        for(int i=0;i<length;i++)
        {
            if(i%2==0)
                count++;
        }
        int a=0;
        int b=count;
        int[] temp=new int[length];
        for(int j=0;j<length;j++){
            if(array[j]%2==0)
                temp[b++]=array[j];
            else
                temp[a++]=array[j];
        }
        for(int i=0;i<length;i++){
            array[i]=temp[i];
        }
        for(int i=0;i<length;i++)
        {
            System.out.println(array[i]);
        }
    }
}

运行结果
在这里插入图片描述
方法二
第二个方法,不用创建数组,在原始数组上,确定起始,终止位置,从后进行遍历,这样的速度可以加快寻找过程。

public class shuzu2 {
    public static void main(String[] args){
        int[] array={1,2,3,4,5,6,7,8};
        int length=array.length;
        for(int i=0;i<length;i++){
            for(int j=length-1-i;j>0;j--){
                if(array[j]%2==1&&array[j-1]%2==0){
                    int temp=array[j];
                    array[j]=array[j-1];
                    array[j-1]=temp;
                }
            }
        }
        for(int i=0;i<length;i++){
            System.out.println(array[i]);
        }
    }
}

运行结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值