笔试题——C++字符排序

题目:字符排序

题目介绍:输入一组以空格隔开的字数串,将它们奇数位升序排序,偶数位降序排序,再重新输出成新的字数串。

例:

输入:

4 6 2 3 6 7 8 1

奇数位:4 2 6 8 ——2 4 6 8

偶数位:6 3 7 1 ——7 6 3 1

输出:

2 7 4 6 6 3 8 1

分析:未预定输入位数,数组处理即可。

代码:

 1 #include <iostream>
 2 #include <string>
 3 #include <conio.h>
 4 using namespace std;
 5 int main()
 6 {
 7     char a[49],b[49],d[49];
 8     int i = 0;
 9     int k = 0;
10     int l = 0;
11     char mid;
12     char c;
13     while ((c=_getch()) != '
')
14     {
15         if (c >= '0'&&c <= '9')
16         {
17             a[i]=c;
18             cout << a[i] << " ";
19             i++;
20         }
21     }
22     cout << endl;
23     for (int j = 0; j < i;j++)
24     {
25         if (j % 2 == 0)//奇数位
26         {
27             b[k] = a[j];
28             k++;
29         }
30         if (j % 2 == 1)//偶数位
31         {
32             d[l] = a[j];
33             l++;
34         }
35     }
36     for (int j = 0; j < k; j++)
37     {
38         for (int e = 0; e < k; e++)
39         {
40             if (b[j] > b[e] &&( j < e))
41             {
42                 mid = b[j];
43                 b[j] = b[e];
44                 b[e] = mid;
45             }
46         }
47     }
48     for (int j = 0; j < k; j++)
49     {
50         cout << b[j] << " ";
51     }
52     cout << endl;
53     for (int j = 0; j < l; j++)
54     {
55         for (int e = 0; e < l; e++)
56         {
57             if (d[j] < d[e] && (j < e))
58             {
59                 mid = d[j];
60                 d[j] = d[e];
61                 d[e] = mid;
62             }
63         }
64     }
65     for (int j = 0; j < l; j++)
66     {
67         cout << d[j] << " ";
68     }
69     cout << endl;
70     for (int j = 0; j < i; j++)
71     {
72         if (b[j] >= '0'&&b[j] <= '9'&&d[j] >= '0'&&d[j] <= '9')
73         {
74             cout << b[j] << " " << d[j] << " ";
75         }
76     }
77 }

结果:

分析:若要进一步优化代码,可以从排序入手,比如设置一个max函数输入为a,b判定大小返回true或者false;或者直接用排序函数sort;将奇数位和偶数位分别储存进不同数组好处是思路清晰,如果优化可以放在一个数组中用if来区分奇偶排序。

原文地址:https://www.cnblogs.com/ljy1227476113/p/9658231.html