C语言编程…数组排列问题……求帮忙
编写程序,从键盘上读取10个数字存放到a数据中,然后对a数组中的10个元素,分别对其中的偶数进行从小到大排列,对其中的奇数从大到小排列,然后展现在屏幕上。要求:排序不影响数组中元素内容的奇偶性,即原来位置上是偶数,依然是偶数,是奇数,仍然是奇数。
#include<stdio.h> #include<string.h> main() { int a[10] = { 0 }, flagou[10] = {0}, flagji[10] = { 0 }; int i = 0, j = 0; int maxou = 0, maxji = 0; int count = 0; printf("请输入十个整数:\n"); for (i = 0; i < 10; i++) { scanf("%d",&a[i]); if (a[i] % 2 == 0) { flagou[maxou++] = i; } else { flagji[maxji++] = i; } } for (i = 0; i < maxou-1; i++) { for (j = 0; j < maxou-1; j++) { if (a[flagou[j]] > a[flagou[j + 1]]) { count = a[flagou[j]]; a[flagou[j]] = a[flagou[j + 1]]; a[flagou[j + 1]] = count; } } } for (i = 0; i < maxji - 1; i++) { for (j = 0; j < maxji - 1; j++) { if (a[flagji[j]] > a[flagji[j + 1]]) { count = a[flagji[j]]; a[flagji[j]] = a[flagji[j + 1]]; a[flagji[j + 1]] = count; } } } printf("排列后:\n "); for (i = 0; i < 10; i++) { printf("%d ", a[i]); } printf("\n"); return 0; }
#include<stdio.h> #include<string.h> void sort(int a[], int flag[], int count); int main() { int a[10] = { 0 }, flagou[10] = {0}, flagji[10] = { 0 }; int i = 0, j = 0; int maxou = 0, maxji = 0; int count = 0; printf("请输入十个整数:\n"); for (i = 0; i < 10; i++) { scanf("%d",&a[i]); if (a[i] % 2 == 0) { flagou[maxou++] = i; } else { flagji[maxji++] = i; } } sort(a, flagou, maxou); sort(a, flagji, maxji); printf("排列后:\n "); for (i = 0; i < 10; i++) { printf("%d ", a[i]); } printf("\n"); return 0; } void sort(int a[], int flag[], int n) { int i = 0, j = 0, count = 0; for (i = 0; i < n - 1; i++) { for (j = 0; j < n - 1; j++) { if (a[flag[j]] > a[flag[j + 1]]) { count = a[flag[j]]; a[flag[j]] = a[flag[j + 1]]; a[flag[j + 1]] = count; } } } }
#include<stdio.h> #define ASCENDING 0 #define DESCENDING 1 #define ODDNUMBER 0 #define EVENNUMBER 1 void _Sort(int n[], int m, int parity, int order) { for (int i=0; i<m; i++) { if ((parity == ODDNUMBER) ? (n[i]%2 != 0) : (n[i]%2 == 0)) { for (int j=i+1; j<m; j++) { if ((parity == ODDNUMBER) ? (n[j]%2 != 0) : (n[j]%2 == 0)) { if ((order == ASCENDING) ? (n[i] > n[j]) : (n[i] < n[j])) { int tmp = n[j]; n[j] = n[i]; n[i] = tmp; } } } } } } main() { //int n[] = {1,8,3,6,5,4,7,10,9,2}; int n[] = {1,1,3,8,8,6,3,6,5,5,2,4,7,7,9,10,2,9}; int m = sizeof(n)/sizeof(int); for (int i=0; i<m; i++) printf("%d ", n[i]); printf("\n"); _Sort(n, m, ODDNUMBER, DESCENDING); _Sort(n, m, EVENNUMBER, ASCENDING); for (int i=0; i<m; i++) printf("%d ", n[i]); }