c++ - 按 Alpha 顺序对 2D 字符数组进行排序?

标签 c++ bubble-sort

我正在尝试将二维名称数组按字母顺序排序,但我无法拼接以使其正常工作。

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

我尝试过 googleing 和其他东西,但每个提示都说使用 vector 或字符串变量..但我仅限于使用 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

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

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

最佳答案

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

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 循环输出数组。最后一次迭代只会产生垃圾值。

关于c++ - 按 Alpha 顺序对 2D 字符数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9750011/

相关文章:

Java:反向排序方法

java - 使用冒泡排序对数组进行排序,发现错误 - 需要 : variable,:值

c++ - STL 映射与 vector 的迭代器访问性能?

c++ - 将 vector<int> 转换为字符串

c++ - 将一组字符串转换为一个简单的字符串 C++

c++ - 如何使用 boost::serialization 序列化 TAO::unbouded_basic_string_sequence<T>?

algorithm - J:冒泡排序默认实现中的自引用

c++ - 一次读取一行 C++

c - 在 C 中用空值对数组进行冒泡排序

c - 当我给出“否”时,我会得到随机数。 > 55