14. Reorder array so odd numbers come before even numbers

 Question : Input an array of integers and implement a function to adjust the order of the numbers in the array so that all odd numbers are in the first half of the array and all even numbers are in the second half of the array

  Ideas :
  1. Define two pointers p1, p2, p1 starts from the first point of the array, and p2 starts from the last bit.
  2. When p1 points to an even number and p2 points to an odd number, the two are swapped.
  3. When p2 > p1, the adjustment ends.

  Test cases :
  1. Functional test
  2. Special input test (NULL, the number contains only one number)

#include<iostream>
using namespace std;

void Reorder(int *pData, unsigned int length)
{
    if (pData == NULL || length == 0)
    {
        return;
    }

    int *pBegin = pData;
    int *pEnd = pData + length -1;

    while (pBegin < pEnd)
    {
        //向后移动pBegin,直到它指向偶数
        while (pBegin < pEnd && (*pBegin & 0x1) != 0) //与1做与运算,判断是否为奇数
            pBegin++;

        //向前移动pEnd,直到它指向奇数
        while (pBegin < pEnd && (*pEnd & 0x1) == 0)
            pEnd--;

        if (pBegin < pEnd)
        {
            int temp = *pBegin;
            *pBegin = *pEnd;
            *pEnd = temp;
        }
    }
}

void test1()
{
    int a[5] = {1, 2, 3, 4, 5};

    Reorder((int*)a, 5);
    for (int i = 0; i < 5; i++)
    {
        cout << a[i] << " ";
    }
    cout << endl;
}

void test2()
{
    Reorder(NULL, 0);

    cout << endl;
}

void test3()
{
    int length = 1;
    int a[] = {1};

    Reorder((int*)a, length);
    for (int i = 0; i < length; i++)
    {
        cout << a[i] << " ";
    }

    cout << endl;
}

int main()
{
    test1();
    test2();
    test3();

    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324399681&siteId=291194637