让数组中奇数位于偶数前面

//双指针法,分别从后往前和从前往后查找,找到奇数和偶数,交换它们,然后最后将排好的数组打印出来。

#include<iostream>
using namespace std;

void rearray(int* array, int length)
{
    if (array == nullptr || length == 0)
        return;

    int *left = array;
    int *right = array + length - 1;
    while (left < right)
    {
        while ((left < right) && (*left % 2 == 1))
            left++;
        while (left < right && *right % 2 == 0)
            right--;
        if (left < right)
        {
            int temp = *left;
            *left = *right;
            *right = temp;
        }
    }
    for (int i = 0; i < length; i++)
    {
        cout << array[i];
    }
    cout << endl;


}

int main()
{
    int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int length = 10;
    rearray(array,length);
    system("pause");
    return 0;

}

发布了27 篇原创文章 · 获赞 8 · 访问量 2121

猜你喜欢

转载自blog.csdn.net/hgxy123/article/details/104201128