zoukankan      html  css  js  c++  java
  • 将数组的奇数放到偶数前面

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

    思路:

    声明两个指针,一个指向该数组的头,另一个指向该数组的尾,将头指针指向的第一个偶数和尾指针指向的第一个奇数交换即可,直到头指针大于尾指针跳出循环。

    代码如下:

    void tiaozheng(int *data,unsigned int length)
    {
        if(data==NULL||length<=0)
            throw exception("参数错误!");
        int *begin=data;
        int *end=data+length-1;
        //将begin的第一个偶数和end的第一个奇数交换,直到begin>=end,这时所有奇数都在偶数前面
        while(begin<end)
        {
            //begin指向的数为奇数则begin++,是偶数则跳出循环
            while(begin<end && (*begin & 0x1)==1)
                begin++;
            //end指向的数为偶数则end++,是奇数数则跳出循环
            while(begin<end && (*end & 0x1)==0)
                end--;
            //如果begin<end则交换这两个数字
            if(begin<end)
            {
                int temp=*begin;
                *begin=*end;
                *end=temp;
            }
        }
    }

    上面的方法只能用于区分奇数和偶数,程序的通用性不高,例如如果需要将正数和负数分开则需要重新写一个函数,下面是一个用于解决此类问题的通用模板,如果需要划分正负数的话,将函数的参数func更改为判断正负数的函数即可。(本例中传入判断奇偶数的方法isjishu)

    代码如下:

    //判断是否是奇数的函数,奇数返回true,偶数返回false
    bool isjishu(int x)
    {
        if(x & 0x1==1)
            return true;
        else if(x & 0x1==0)
            return false;
    }
    //打印函数
    void print(int *data,int length)
    {
        int *begin=data;
        int count=0;
        while(count<length)
        {
            cout<<*begin<<"  ";
            begin++;
            count++;
        }
        cout<<endl;
    }
    //使用通用的模板解决此类问题
    void tiaozheng2(int *data,unsigned int length,bool (*func)(int))
        {
        if(data==NULL||length<=0)
            throw exception("参数错误!");
        int *begin=data;
        int *end=data+length-1;
        //将begin的第一个偶数和end的第一个奇数交换,直到begin>=end,这时所有奇数都在偶数前面
        while(begin<end)
        {
            //begin指向的数为奇数则begin++,是偶数则跳出循环
            while(begin<end && func(*begin))
                begin++;
            //end指向的数为偶数则end++,是奇数数则跳出循环
            while(begin<end && !func(*end))
                end--;
            //如果begin<end则交换这两个数字
            if(begin<end)
            {
                int temp=*begin;
                *begin=*end;
                *end=temp;
            }
        }
    }

    测试代码及运行结果:

    int main()
    {
        int data[5]={1,2,3,4,5};
        print(data,5);
        tiaozheng2(data,5,isjishu);
        print(data,5);
        return 0;
    }

  • 相关阅读:
    pytest.mark.parametrize里面indirect参数详细解释
    linux环境安装python环境
    gitlab怎么给别人新增项目权限
    VMware虚拟机下的CentOS7如果Ping不通百度,解决办法
    ip configuration could not be reserved (no available address timeout etc.)虚拟机连接不上网卡解决办法
    虚拟机安装教程
    auto_now与auto_now_add之间的区别
    【二分答案】洛谷P2678 [NOIP2015 提高组] 跳石头/P1824 进击的奶牛/P2440木材加工/P1873 砍树
    团体程序设计天梯赛PTA L2-021点赞狂魔
    团体程序设计天梯赛PTA L2-020功夫传人
  • 原文地址:https://www.cnblogs.com/runninglzw/p/4522561.html
Copyright © 2011-2022 走看看