【问题标题】:Sort odd and even numbers separatedly and move all odd numbers in front将奇数和偶数分开排序,将所有奇数移到前面
【发布时间】:2016-01-27 16:25:30
【问题描述】:

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

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

我的问题是我们是否可以通过一步而不是两步来解决问题

【问题讨论】:

  • 绝对可以一步完成,只需使用所有奇数都小于偶数的比较。
  • 你的号码可以有多长(length)

标签: algorithm


【解决方案1】:

我认为您熟悉 C++。看我的code sn-p,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;
}

如有任何困惑,欢迎 cmets。

【讨论】:

  • 我认为您的解决方案仅适用于 0 到 9 的数字。问题是关于任何整数。
  • @JoeC。我理解错了,这就是它这样做的原因。好的。让我解决它。
【解决方案2】:

在 C++ 中的 &lt;algorithm&gt; 库下,您可以使用 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; });

产生了一个相当简洁的解决方案。

【讨论】:

    【解决方案3】:

    是的,可以一步完成。

    编写自己的比较函数,并在 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;
            }
        } 
    }
    

    【讨论】:

      【解决方案4】:

      你只需要一个用于排序的comp-function:

      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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-04
        • 1970-01-01
        • 1970-01-01
        • 2012-01-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多