对字符数组中的单词进行排序

Sorting words in a character array

本文关键字:单词进 排序 字符 数组      更新时间:2023-10-16

对于给定的数组,我需要编写一个函数来按字母顺序对单词进行排序:

char strings [][10] = {
    "hello",
    "world",
    "computers",
    "are",
    "awesome"
};

我尝试使用插入排序来sortWords编写函数,但我认为我的交换函数不起作用:

void swap(char *e1, char *e2) {
    int tmp = *e1;
    *e1 = *e2;
    *e2 = tmp;
}
void sortWords( char (* words2Darray)[10], unsigned short length ) {
    unsigned int i, curPos;
    char curChars[10];
    for(i = 1; i < length; i++) {
        // Copy the current word into curChars
        strncpy_s(curChars, words2Darray[i], 10);
        curPos = i;
        // Compare and move the word to the correct position
        while(curPos > 0 && strcmp(curChars, words2Darray[i-1]) > 0) {
            swap(words2Darray[curPos], words2Darray[curPos-1]);
            curPos--;
        }
    }
}

我尝试使用本地 Windows 调试器调试我的代码,发现curChars正在正确复制。

有人可以向我解释我做错了什么以及我应该如何解决这个问题吗?我不允许在这个问题中使用std::string请不要提供完整的解决方案!

你可以

只使用std::sort

std::sort(std::begin(strings), std::end(strings), cmp);

这需要一个比较器。我根据strcmp鞭打了一个.

在 IdeOne 上观看直播

#include <algorithm>
#include <iostream>
#include <cstring>
int main()
{
    char const* strings[] = {
        "hello",
        "world",
        "computers",
        "are",
        "awesome"
    };
    struct { 
        bool operator()(char const* a, char const* b) const {
            return (a && b)? 0 > strcmp(a,b) : a < b;
        }
    } cmp;
    std::sort(std::begin(strings), std::end(strings), cmp);
    for (auto& s : strings)
        std::cout << s << "n";
}

请注意,我冒昧地将数组元素char*而不是char[]。这是出于Carl Norum指出的原因。

你不是交换字符串,而是交换字符串的第一个字符。 如果要按值传递,则需要如下内容:

void swap(char **e1, char **e2) {
    char *tmp = *e1;
    *e1 = *e2;
    *e2 = tmp;
}

然后使用它:

swap(&words2Darray[curPos], &words2Darray[curPos-1]);

或者,您可以将swap调用保留原样并使用引用:

void swap(char *&e1, char *&e2) {
    char *tmp = e1;
    e1 = e2;
    e2 = tmp;
}

(我认为没错——我的C++生锈了。 我会做一个测试来确定。