整數奇偶數排序(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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章