@[TOC] [sort C/C + +] integer parity sort
[sort C/C + +] integer parity sort
Basic questions of sorting algorithm
Enter 10 integers separated by spaces. Output after reordering (also separated by spaces) requires:
1. Output the odd numbers first, and arrange them from large to small;
2. Then output even numbers and arrange them from small to large.
Method 1:
Input numbers one by one, and judge each number. And put it into different arrays, and output after sorting.
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; bool cmp(int a,int b) //sort comparison factor { return a>b; } int main() { int even[10],odd[10],n;//Create an array of odd and even numbers while(~scanf("%d",&n)) { int a=0,b=0; if(n%2==0) even[a++]=n; else odd[b++]=n; for(int i=0;i<9;i++) { scanf("%d",&n); if(n%2==0) even[a++]=n; else odd[b++]=n; } sort(even,even+a); sort(odd,odd+b,cmp); for(int i=0;i<b;i++) printf("%d ",odd[i]); for(int i=0;i<a;i++) { printf("%d",even[i]); if(i!=a-1) printf(" "); } printf("\n"); } return 0; }
Method two:
First put ten numbers into the array, and judge the parity as a whole.
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int main() { int a[10]; for (int i=0;i<10;i++) { scanf("%d",&a[i]); } int sin[10]={0}; int dou[10]={0}; int p=0;int q=0; for (int i=0;i<10;i++) { if (a[i]%2==0) { dou[p]=a[i]; p++; } else { sin[q]=a[i]; q++; } } sort(sin,sin+q); sort(dou,dou+p); for (p=0;p<10-p;p++) { printf("%d ",sin[p]); } for (q=0;q<10-q;q++) { printf("%d ",dou[q]); } printf("\n"); return 0; }