按Alpha顺序对2D字符数组进行排序
Sorting a 2D Char Array in Alpha order?
我正在尝试按字母顺序对一个2D名称数组进行排序,但我无法缝合以使其工作。
我对字母使用了冒泡排序,这对名字的第一个字母进行了很好的排序,但其中3个名字以同一个字母开头,它们仍然是无序的。
我试过谷歌搜索之类的东西,但每个ting都说要使用向量或字符串变量。。但我仅限于使用2d字符数组。。
有什么想法吗?
这是我目前拥有的几乎可以工作的代码:
using namespace std;
int main (){
char heroes[11][17] = { "Captain America", "Thor", "Wolverine", "Cyclops", "Goliath", "Beast", "Angel", "Colossus", "Hulk", "Quicksilver", "Ironman"};
cout<<"Printing the array as is"<<endl<<endl;
for (int i=0; i<12; i++){
cout<<heroes[i]<<endl;
}
cout<<endl<<"Ordering the heroes in Alphabetical order"<<endl<<endl;
char temp = NULL;
// bubble sort
for(int i=0;i<11;i++){
for(int j=0; j<(11-1); j++){
if (heroes[i][0] < heroes[j][0]){
for (int k=0; k<17-1; k++){
swap(heroes[i][k], heroes[j][k]);
}
}
}
}
cout<<"Printing the array Sorted"<<endl<<endl;
for (int i=0; i<12; i++){
cout<<heroes[i]<<endl;
}
// Pause
cout<<endl<<endl<<endl<<"Please Close Console Window"<<endl;
cin.ignore('n', 1024);
return(0);
}
好吧,我搞定了!!!
http://ideone.com/ugLZ7
这是代码。。。(顺便说一句,我如何在这个表格上张贴代码?)
它几乎完全相同,但使用了完整的字符串比较和副本。
您似乎没有正确理解冒泡排序。首先,您应该只比较相邻的元素,其次,您需要在第一个字符之外检查是否匹配两个元素。我做了必要的修改,正确工作的代码的相关部分是:
int n=11,k,l;
for(int i=0;i<n-1;i++){
for(int j=0; j<n-i-1; j++){
l = min(strlen(heroes[j]),strlen(heroes[j+1]));
for(k=0;k<l;++k)
if(heroes[j+1][k]<heroes[j][k]){ swap(heroes[j],heroes[j+1]); break; }
else if(heroes[j+1][k]>heroes[j][k]) break;
if(k==l and strlen(heroes[j])>strlen(heroes[j+1]))
swap(heroes[j],heroes[j+1]);
}
}
PS:您不需要使用for循环输出具有12次迭代的数组。上一次迭代只生成垃圾值。
试着依靠标准库来为您完成繁重的工作,您正在编写的实际上是带有std::cout
的C,这是不鼓励的。
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<std::string> > heroes {
"Captain America", "Thor", "Wolverine", "Cyclops",
"Goliath", "Beast", "Angel", "Colossus", "Hulk",
"Quicksilver", "Ironman"
};
std::sort(heroes.begin(), heroes.end());
std::copy(heroes.begin(), heroes.end(),
std::ostream_iterator<std::string>(std::cout, ", "));
return 0;
}
请注意,如果您没有C++11,则需要使用手动将元素添加到向量中
std::vector<std::string> > heroes;
heroes.push_back("Captain America");
...
使用strcmp函数&气泡排序方法:
char temp[20];
int size = 11;
for(int i=1; i<size; i++)
{
for(int j=0; j<size-i;j++)
{
if(strcmp(heroes[j],heroes[j+1]) > 0)
{
strcpy(temp, heroes[j]);
strcpy(heroes[j], heroes[j+1]);
strcpy(heroes[j+1], temp);
}
}
}
相关文章:
- 显示错误输出的简单数组排序程序
- C 使用单个函数对具有多种值类型的数组排序
- 2D数组排序,空格打乱顺序
- C 2D数组排序
- C++数组排序 - 将"bbba"和"0001"视为不正确排序的问题
- 数组排序功能
- CString 数组排序
- 简单的数组排序/检查 划分和征服版本
- C++ 中的多维数组排序
- 选择在++中对并行数组排序
- C++:二维指针数组排序:选择排序不适用于某些实例
- C++字符串数组排序
- C++中的指针数组排序算法
- 在VC++6中使用向量进行数组排序时出错,而在VC++2012中没有错误
- 将索引数组排序为主数组
- 数组排序、数组输入、数组输出
- C++数组排序,内存错误
- 在嵌入式系统上将数组排序功能从c++移植到c
- 基于其他int数组排序
- 多维数组排序c++奇怪行为