编写一个程序以按字母顺序对名称进行排序和显示(使用选择排序)。程序提示用户输入要搜索的名称(使用二进制搜索)。该程序还会对名字和姓氏的第一个字符进行大写校正。
我只能弄清楚如何使用算法库,但是我不允许使用它。
#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;
}
答案 0 :(得分:0)
首先,这不是任何排序算法,但与冒泡排序(一种耗时的算法)接近。同样,您将以随机方式处理字符,而不是字符串。 看看我所做的修改,它将仅对您的数组排序
#include <iostream>
#include <string>
using namespace std;
int main() {
const int SIZE = 20;
string temp;
int i, j;
string arr[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" };
for (i = 1; i < SIZE; i++)
{
for (j = 1; j < SIZE; j++)
{
if ( arr[j-1] > arr[j])
{
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
for (int j = 0; j < SIZE; j++) {
cout << arr[j] << endl;
}
system("pause");
return 0;
}
答案 1 :(得分:0)
您说您需要使用“选择排序”,但是您正在使用“气泡排序”。我在两个循环(for)和字符串交换(运动)上都修改了您的程序。
SharedPreferences prefs = await SharedPreferences.getInstance();
yourStringList = prefs.getStringList('your_string_list_key') ?? List<String>();
真正的“选择排序”具有比较复杂度O(n ^ 2)和运动复杂度O(n)。我相信正确的实现方式应该是:
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main() {
const int SIZE = 20;
string temp;
int i, j;
string arr[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" };
for (i = 0; i < (SIZE - 1); i++)
{
for (j = (i+1); j < SIZE; j++)
{
if ( arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for (int j = 0; j < SIZE; j++) {
cout << arr[j] << endl;
}
system("pause");
return 0;
}
解释代码:字符串是一个C ++类,其中包含字符数组。语句“ string arr [SIZE]”是大小为SIZE的字符串数组。您可以在“ http://www.cplusplus.com/reference/string/string/”处引用字符串类。
代码中的另一个问题是关于排序的问题。 “选择排序”通过将一个元素与后续元素进行比较来对列表进行排序,因此您的第二个循环是错误的,它应该是:“ for(j =(i + 1); j 最后,只需要完成整个j操作即可进行交换(移动)。