整数奇偶排序 【简单 / sort 】

在这里插入图片描述
https://www.nowcoder.com/practice/bbbbf26601b6402c9abfa88de5833163?tpId=40&tqId=21398&rp=1&ru=%2Fta%2Fkaoyan&qru=%2Fta%2Fkaoyan%2Fquestion-ranking&tab=answerKey

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int a[10];
int b[10];//偶数 
int c[10];//奇数
bool cmp(int a,int b)
{
    
    
	return a>b;
} 
int main(void)
{
    
    
	int i,j,k;
	j=k=0;
	for(i=0;i<10;i++) 
	{
    
    
		cin>>a[i];
		if(a[i]%2==0)
			b[j++]=a[i];
		else
			c[k++]=a[i];	
	}
	sort(c,c+k,cmp);
	sort(b,b+j);
	for(i=0;i<k;i++)
		cout<<c[i]<<" ";
	for(i=0;i<j;i++)
		cout<<b[i]<<" ";	 
	return 0;
} 

一种比较叼的写法

//充分发挥sort的能力嘛,cmp中就可以把所有逻辑写清楚了
#include<cstdio>
#include<algorithm>
using namespace std;
bool cmp(int x,int y)
{
    
    
    if(x&1 && y&1)    //如果是奇数就大到小
        return x>y;
    if(x%2==0 && y%2==0)    //好像用位运算判断偶数不好使??
        return x<y;
    if(x&1)        //奇数在前
        return true;
    else
        return false;
}
 
int main()
{
    
    
    int array[10];
    while(scanf("%d",&array[0])!=EOF)
    {
    
    
        for(int i = 1; i < 10; i++)
            scanf("%d",&array[i]);
        sort(array,array+10,cmp);    //sort很强的啊
        for(int i = 0; i<9; i++)
            printf("%d ",array[i]);
        printf("%d\n",array[9]);
    }//while
    return 0;
}

猜你喜欢

转载自blog.csdn.net/bettle_king/article/details/115408441