把数组中的奇数放到偶数之前

案例

数组内容:3 4 4 6 8 2 1 1 1

调换奇偶:3 1 1 1 8 2 4 4 6

 

思路

源于快速排序

方式1

参考代码

#include <iostream>
#include <cstring>
using namespace std;

bool IsOdd(int num)
{
    return num % 2 == 1 ? true : false;
}
bool changeArray(int *a, int size)
{
    if(size <= 0)
        return false;
    int oddPartition = -1;
    int cur = 0;
    for(; cur < size; ++cur)
    {
        if(IsOdd(a[cur]))
        {
            if(oddPartition + 1 != cur)
            {
                int tmp = a[oddPartition+1];
                a[oddPartition]= a[cur];
                a[cur] = tmp;
            }
            ++oddPartition;
        }
    }
    return true;
}


int main()
{
    int a[] = {3, 4, 4, 6, 8, 2, 1, 1, 1};
    int size = sizeof(a) / sizeof(int);

    for(int i = 0; i < size; ++i)
        cout << a[i] << " ";
    cout << endl;

    changeArray(a, size);
    for(int i = 0; i < size; ++i)
        cout << a[i] << " ";
    cout << endl;
}
    

 

方式2

参考代码

#include <iostream>
#include <cstring>
using namespace std;

bool IsOdd(int num)
{
    return num % 2 == 1 ? true : false;
}
bool changeArray(int *a, int size)
{
    if(size <= 0)
        return false;
    int beg = 0, end = size -1;
    while(beg < end)
    {
        while(beg < end && IsOdd(a[beg]))
            ++beg;
        while(beg < end && !IsOdd(a[end]))
            --end;
        if(beg < end)
        {
            int tmp = a[beg];
            a[beg] = a[end];
            a[end] = tmp;
        }
    }
    return true;
}


int main()
{
    int a[] = {3, 4, 4, 6, 8, 2, 1, 1, 1};
    int size = sizeof(a) / sizeof(int);

    for(int i = 0; i < size; ++i)
        cout << a[i] << " ";
    cout << endl;

    changeArray(a, size);
    for(int i = 0; i < size; ++i)
        cout << a[i] << " ";
    cout << endl;
}
    

扩展

不是奇偶问题,别掉条件

比如正负,需要把IsOdd()函数换成判断正负的函数;

比如被5整除,需要把IsOdd()函数换成判断被5整除的函数;

。。。。。。

这是一类问题,可以给出一个模式来解决。如下

#include <iostream>
using namespace std;

bool isEven(int val)
{
    return ((val & 0x1) == 0) ? true : false;
}
void ReOrder(int *a, int size, bool (*func)(int))
{
    if (a == NULL || size <= 0)
        return;
    int beg = 0, end = size-1;
    while (beg < end)
    {
        while (beg < end && !func(a[beg]))
            ++beg;
        while (beg < end && func(a[end]))
            --end;
        if (beg < end)
            swap(a[beg], a[end]);
    }
}
void ReOrderOddEven(int *a, int size)
{
    ReOrder(a, size, isEven);
}
    
void tranverse(int *a, int size)
{
    if (a == NULL || size <= 0)
        return;
    for (int i = 0; i < size; ++i)
        cout << a[i] << " ";
    cout << endl;
}
int main()
{
    int a[] = {3, 2, 5, 2, 8, 3, 3, 0, 9};
    int size = sizeof(a) / sizeof(int);
    tranverse(a, size);
    ReOrderOddEven(a, size);
    tranverse(a, size);
}

 

 

posted @ 2014-03-18 10:51  jihite  阅读(4463)  评论(2编辑  收藏  举报