【发布时间】:2019-05-13 12:42:09
【问题描述】:
编写一个程序以按字母顺序对名称进行排序和显示(使用选择排序)。程序提示用户输入要搜索的名称(使用二进制搜索)。该程序还对名字和姓氏的第一个字符的大写进行了更正。
我只能弄清楚如何使用算法库,但我不允许使用它。
#include <iostream>
#include <string>
#include <string.h>
#include <conio.h>
using namespace std;
int main() {
const int SIZE = 20;
char temp;
int i, j;
bool madeAswap;
char arr[SIZE][SIZE] = { "Collins, Bill", "Smith, Bart", "Michalski, Joe",
"Griffin, Jim","Sanchez, Manny", "Rubin, Sarah", "Taylor, Tyrone",
"Johnson, Jill","Allison, Jeff", "Moreno, Juan", "Wolfe, Bill",
"Whitman, Jean","Moretti, Bella", "Wu, Hong", "Patel, Renee",
"Harrison, Rose","Smith, Cathy", "Conroy, Pat", "Kelly, Sean", "Holland, Beth" };
do {
madeAswap = false;
for (i = 1; i < SIZE; i++)
{
for (j = 1; j < SIZE; j++)
{
if (strcmp(arr[j - 1], arr[j]) > 0)
{
temp = arr[i][i];
arr[i][i] = arr[i + 1][i + 1];
arr[i + 1][i + 1] = temp;
madeAswap = true;
}
}
}
}while (madeAswap);
for (int j = 0; j < SIZE; j++) {
cout << arr[j][j] << endl;
}
system("pause");
return 0;
}
【问题讨论】:
-
1) 使用 std::string。 2) 使用 std::swap。 3)这看起来不像选择排序。看起来更像冒泡排序。 4) 数组索引从 0 开始。
-
选择排序是 O(N^2) 并且有两个循环。外部循环遍历索引 i。内部循环从 i 迭代到 N 并找到 i 到 N 范围内的最小元素。你取这个元素并与元素 i 交换。见this answer
-
"[我] 不允许使用 [标准库]。"那你连所谓的 I/O 都做不了。
-
顺便说一句,由于
do... while(madeAswap)循环,您的代码尝试排序两次。这个逻辑是错误的。而且你没有交换字符串。你在交换角色。为什么temp声明为char?再次,让您的生活更轻松。使用 std::string 和 std::swap -
您的问题缺少具体问题。您当前的代码如何出现故障?您具体在寻求什么帮助(假设您没有要求我们为您做作业)?