分别对奇数和偶数进行排序,并在前面移动所有奇数

时间:2015-10-28 02:22:24

标签: algorithm

例如,如果输入数组是   832461905 输出是   1357902468

我认为这可以分两步完成 1)排序数据   012345678 2)通过保持顺序移动偶数前面的奇数   为此,我们可以有两个指针   最初一个指向开头,另一个指向结尾    移动头部工具偶数找到    移动尾部直到找到奇数    在指针处交换数据    执行上述操作直到两个指针相遇

我的问题是,如果我们可以通过使用一步而不是两步来解决问题

4 个答案:

答案 0 :(得分:2)

您需要的只是一个用于排序的小功能:

bool comp(int x, int y)
{
    if (x % 2 == y % 2) return x < y;
    return x % 2 > y % 2;
}
...
sort(your_array.begin(), your_array.end(), comp);

答案 1 :(得分:1)

是的,可以一步完成。

编写自己的比较函数,并在C ++中使用std::sort

sort(data.begin(),data.end(),comp);

bool comp(int x,int y)
{
    if (x%2==0)     
    {
        if(y%2==0)
        {
            return x<y;   // if both are even
        }
        else
        {
            return false;    // if only x is even
        }
    }
    else
    {
        if(y%2==0)
        {
            return true;
        }
        else
        {
            return x<y;
        }
    } 
}

答案 2 :(得分:0)

我在考虑你熟悉 C ++ 。请参阅我的代码代码段,yes可以在一个步骤中完成:

#include <iostream>
#include <stdio.h>
#include <algorithm>

bool function(int a, int b) {
    if(a%2 != b%2) {                /* When one is even and another is odd */   
        if(a&1) {                   
            return true;
        } else {
            return false;
        }
    } else {                        /* When both are either odd or even */
        return (a<b);
    }
}

int main() {
    int input[10005];                 /* Input array */
    int n = -1, i;

    /* Take the input */
    while(scanf("%i", &input[++n]) != EOF);

    /* Sort according to desire condition */
    std::sort(input, input+n, function);

    /* Time to print out the values */
    for(i=0; i<n; i++) {
        std::cout << input[i] << " ";
    }

    return 0;
}

任何混乱,评论最受欢迎。

答案 3 :(得分:0)

在C ++中的<algorithm>库下,您可以使用sort对数字进行排序,然后stable_partition按奇数和偶数分隔。

像这样:

auto arr = std::valarray<int>{8,3,2,4,6,1,9,0,5};
std::sort(std::begin(arr), std::end(arr));
std::stable_partition(std::begin(arr), std::end(arr), [](int a){ return a % 2; });

导致一个相当简洁的解决方案。