计算概论(A) / 自由练习 1002:奇偶排序

1002:奇偶排序

总时间限制:1000ms 内存限制: 65536kB

描述
输入十个整数,将十个整数按升序排列输出,并且奇数在前,偶数在后。
输入
输入十个整数
输出
按照奇偶排序好的十个整数
样例输入
10 9 8 7 6 5 4 3 2 1
样例输出
1 3 5 7 9 2 4 6 8 10
思路

先遍历数组,把元素分成奇偶两部分,奇数都在左边,偶数都在右边,然后使用冒泡排序分别将左右的元素排序,输出即可。

代码
#include <iostream>
using namespace std;
//int n=10;

void Swap(int &a,int &b)
{
    int tmp=a;
    a=b;
    b=tmp;
}

    //double loop to compare from left to right, swap the biggest to the right first.
    // ascending
    // It's important to remember
void BubbleSort(int arr[],int beg, int en)
{
    for(int i=beg;i<=en;i++)  //control comparison times
    {
        for(int j=beg+1;j<=beg+en-i;j++) //pay attention to j's termination time
        {
            if(arr[j]<arr[j-1])
                Swap(arr[j],arr[j-1]);
        }
    }
}
int main()
{
    //input
    int n=10;
    int arr[n];
    for(int i=0;i<n;i++)
        cin>>arr[i];
  // use pointer to separate odd and even
    int left=0,right=n-1;
    while(left<=right)
    {
        bool isLeftOdd=(arr[left]%2==1);
        bool isRightEven=(arr[right]%2==0);
        if(isLeftOdd)
            left++;
        else if(isRightEven)
            right--;
        else if(!isLeftOdd && !isRightEven)
            Swap(arr[left++],arr[right--]);
    }

    //sort the odd and even numbers with bubble sort respectively
        BubbleSort(arr,0,right);
        BubbleSort(arr,right+1,n-1);

    //output
    for(int i=0;i<n;i++)
        cout <<arr[i]<<' ';
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值