整数奇偶数排序(o(n^2)排序算法)

Description
给定10个整数的序列,要求对其重新排序。排序要求:1.奇数在前,偶数在后;2.奇数按从大到小排序;3.偶数按从小到大排序。
Input
输入一行,包含10个整数,彼此以一个空格分开,每个整数的范围是大于等于0,小于等于100。
Output
按照要求排序后输出一行,包含排序后的10个整数,数与数之间以一个空格分开。
Sample Input 1
4 7 3 13 11 12 0 47 34 98
Sample Output 1
47 13 11 7 3 0 4 12 34 98
Time Limit
1000MS
Memory Limit
256MB
由于只有10个排序对象,故用o(n ^ 2) 的初级排序算法就可以解决。 o(n^2)排序算法有很多,我选冒泡排序,因为这个算法比较稳定,本次代码为从前往后冒泡。

#include<stdio.h>
#include<algorithm>
using namespace std;

int a[10];

bool check(int x)//排序规则,true表示需要重排
{//枚举出所有true的情况,剩下的一定是不用重排的
    if(a[x]%2==0&&a[x+1]%2==1)
       return true;
    if(a[x]%2==0&&a[x+1]%2==0&&a[x]>a[x+1])
       return true;
    if(a[x]%2==1&&a[x+1]%2==1&&a[x]<a[x+1])
       return true;
    return false;
}

int main()
{
    for(int i=0;i<10;i++)
    {
        scanf("%d",a+i);
    }
    //排序
    for(int i=10-1;i>0;i--)
       for(int j=0;j<i;j++)
          if(check(j)){
              swap(a[j],a[j+1]);
          }
          
    for(int i=0;i<10;i++)
    {
        printf("%d ",a[i]);
    }
    return 0;
}
原创文章 34 获赞 87 访问量 2724

猜你喜欢

转载自blog.csdn.net/qq_44643644/article/details/105855972
今日推荐