0

我正在尝试按字母顺序对 2D 名称数组进行排序,但我无法缝合以使其正常工作。

我对字母使用了冒泡排序,这可以很好地对名称的第一个字母进行排序,但是其中 3 个名称以相同的字母开头,它们仍然是乱序的。

我已经尝试过 googleing 和其他东西,但每个 ting 都说要使用向量或字符串变量..但我仅限于使用 2d char 数组..

有任何想法吗?

这是我目前几乎可以使用的代码:

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

这是代码...(顺便说一句,我如何在此表单上发布代码?)

它几乎完全相同,但使用完整的字符串比较和副本。

4

3 回答 3

1

尝试并依靠标准库为您完成繁重的工作,您正在编写的内容实际上是 C 语言std::cout并且不被鼓励。

#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");
...
于 2012-03-17T12:52:26.443 回答
1

您似乎没有正确理解冒泡排序。首先,您应该只比较相邻元素,其次,如果两个元素匹配,您需要检查第一个字符之外的内容。我进行了必要的修改,正常工作代码的相关部分是:

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:您不需要使用具有 12 次迭代的 for 循环输出数组。最后一次迭代只会产生垃圾值。

于 2012-03-17T12:53:53.663 回答
1

使用 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);
        }
    }
}
于 2016-10-03T14:37:48.757 回答