按字母顺序排列的气泡排序数组
Alphabetical Bubble sorting Array
给定名称数量的输入,我应该使用气泡排序按字母顺序列出它们。然而,我似乎无法得到正确的算法,因为我的输出是以某种随机顺序给出的。我的示例输入是
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;
}
}
以下是一些需要注意的事项。
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交换
目前,您正在交换独立于姓氏的名字。这会导致你的名字混乱不堪。同时交换它们。
相关文章:
- 在气泡排序程序中未声明错误功能
- 气泡排序未正确循环
- 带有枚举方向/类型的气泡排序结构数组
- 在气泡排序中使用递归
- 如何在C++中实现气泡排序?
- 比较迭代器会使程序崩溃,而不会在自定义气泡排序实现中出现错误
- C++气泡排序的问题
- 气泡排序C++ OOP
- OOP 气泡排序C++程序
- 按升序对列表进行排序,C++使用气泡排序
- C++气泡排序
- 此气泡排序代码中的错误是什么?
- 气泡排序 2D 数组
- 如何使用气泡排序从最小到最大对 4 个数组进行排序? C++
- 添加气泡排序代码以排列列表
- 使用向量和气泡排序的动态内存分配
- 带修改(偏移)的气泡排序
- 使用C++进行气泡排序
- 选择排序与气泡排序C++
- 为什么我的气泡排序不适用于双精度数据类型?