奇偶排序
输入若干非负整数数字,请先取出奇数数字按从大到小排序,再取出偶数数字,从小到大排序。
样例输入:12 34 5 7 92 3 8
样例输出: 7 5 3 8 12 34 92
不同语言的解法
1,使用C语言来解决
#include <stdio.h> #include <stdlib.h> #include <string.h> // little -> big int comp1(const void *a, const void *b){ return *(int *)a - *(int *)b; } // big -> little int comp2(const void *a, const void *b){ return *(int *)b - *(int *)a; } int main(){ int odd[1000] = {0}; int even[1000] = {1}; int input = 0; int odd_idx = 0; int even_idx = 0; int i = 0; char a; do{ scanf("%d",&input); if(input % 2){ odd[odd_idx] = input; odd_idx++; }else{ even[even_idx] = input; even_idx++; } a = getchar(); if(a == '\n') break; }while(1); qsort(odd, odd_idx, sizeof(int), comp2); qsort(even, even_idx, sizeof(int), comp1); for(i=0; i<odd_idx; i++){ printf("%d ",odd[i]); } for(i=0; i<even_idx; i++){ printf("%d ", even[i]); } return 0; }
2, 使用C++来完成
#include <iostream> #include <algorithm> using namespace std; int main(){ int input; int odd[1000] = {1}; int even[1000] = {0}; int odd_idx = 0; int even_idx = 0; int i = 0; while(cin>>input, cin.get() != '\n'){ if(input % 2){ odd[odd_idx++] = input; }else{ even[even_idx++] = input; } if(input == '\n'){ break; } } sort(odd, odd + odd_idx); sort(even, even + even_idx); for(i=0; i<odd_idx; i++){ cout<<odd[i]<<" "; } for(i=0; i<even_idx; i++){ cout<<even[i]<<" "; } return 0; }
使用Python来完成
import sys line = sys.stdin.readline() num = [int(x) for x in line.split(' ') if line.strip()] odd = [ x for x in num if x%2 == 1] even = [x for x in num if x%2 == 0] odd.sort(reverse=True) even.sort() print(odd,even)