如果输入了多个名称,我应该使用气泡排序按字母顺序列出它们。但是,我似乎无法使我的算法正确,因为我的输出以某种随机顺序给出。我的示例输入是
5
Alice Hawking
John Smith
Stephen Hawking
Alice Cooper
Jean Smith
代码是
int main() {
int number;
char char1;
char char2;
int measure;
int name1;
int name2;
int flag = 1;
int count = 0, ter = 0;
string tmp;
cin >> number;
string list[number+1][2];
for (int i = 0; i < number; i++) {
cin >> list[i][0] >> list[i][1];
}
// sorting first names
for (int k = 0; k <= number; k++) {
for (int i = 0; i < number - 1; i++) {
// j cannot go beyond the length of the smallest first name
// so measure will be the measure of the smallest first name
if (list[i][0].size() < list[i+1][0].size()) {
measure = list[i][0].size();
} else {
measure = list[i+1][0].size();
}
// convert the each letter of the string by converting
// string to char to int
// flag is to indicate if the two comparisons are not the same
// so that the if loop does not continue
for (int j = 0; flag && j < measure; j++) {
char1 = list[i][0].at(j);
char2 = list[i+1][0].at(j);
name1 = (int)char1;
name2 = (int)char2;
if (name1 > name2) {
tmp = list[i][0];
list[i][0] = list[i+1][0];
list[i+1][0] = tmp;
flag = 0;
}
}
flag = 1;
}
}
// sorting last names
for (int k = 0; k <= number; k++) {
for (int i = 0; i < number - 1; i++) {
// j cannot go beyond the length of the smallest last name
// so measure will be the measure of the smallest last name
if (list[i][1].size() < list[i+1][1].size()) {
measure = list[i][0].size();
} else {
measure = list[i+1][0].size();
}
for (int j = 0; flag && j < measure; j++) {
char1 = list[i][1].at(j);
char2 = list[i+1][1].at(j);
name1 = (int)char1;
name2 = (int)char2;
if (name1 > name2) {
tmp = list[i][1];
list[i][1] = list[i+1][1];
list[i+1][1] = tmp;
flag = 0;
}
}
flag = 1;
}
}
for (int t = 0; t < number; t++) {
cout << list[t][0] << " " << list[t][1] << endl;
}
}
答案 0 :(得分:0)
以下是一些要注意的事项。
1比较字符串。
您是否有任何理由不仅仅使用string
比较来比较名称?从// j cannot go
到flag=
的整个代码(交换除外)可以替换为
if (list[i][0] > list[i+1][0])
2比较两个循环中的第一个和最后一个。
检查同一循环中的姓氏和名字会好得多。类似的东西:
if (list[i][0] > list[i+1][0] || (list[i][0] == list[i+1][0] && list[i][1] > list[i+1][1]) {
}
注意:如果您想按姓氏和名字排序,请更改0
和1
。
3交换
目前,您正在独立于姓氏交换名字。这将导致你的名字混乱。同时交换它们。