C++对 char 指针数组进行排序

发布于 2024-08-25 17:59:29 字数 369 浏览 5 评论 0原文

你能告诉我我的方法有什么问题吗?我最终把同样的东西到处放,但实际上并没有排序。

void sortArrays(){

    int i, j;



    for(i=0; i<counter; i++){



        for( j=0; j<i; j++){

            if( strcmp(title_arr[i], title_arr[j]) < 0){

                char* title_temp = title_arr[i];

                title_arr[j] = title_temp;





            }

        }

    }

Can you tell me what's wrong with my method? I ends up putting the same thing everywhre and it's actually not sorting.

void sortArrays(){

    int i, j;



    for(i=0; i<counter; i++){



        for( j=0; j<i; j++){

            if( strcmp(title_arr[i], title_arr[j]) < 0){

                char* title_temp = title_arr[i];

                title_arr[j] = title_temp;





            }

        }

    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

黑白记忆 2024-09-01 17:59:29

这:

char* title_temp = title_arr[i];

title_arr[j] = title_temp;

相当于:

title_arr[j] = title_arr[i];

你永远不会交换它们,你只是将一个复制到另一个。您应该添加这一行:

title_arr[i] = title_arr[j];

在两者之间。这样,您将用 [j] 覆盖 [i],但 _temp 仍保留 [i] 的旧值,因此您可以将该值复制到 [j] 中,从而交换它们。

我想这也是上算法课的时间。您的算法称为“冒泡排序”算法。它以其简单性而闻名,但在现实环境中,它以效率低下而闻名(技术术语是“teh sux”,真正的技术术语是O(n^2)(“N平方”)性能)。一些更常见(也更高效)的算法包括 Quicksort合并排序,以及 堆排序等等。有关衡量算法可扩展性的更多信息,请参阅有关Big Oh 表示法的文章。*

但是,作为 vava在评论中指出,除非您的作业是编写自己的排序函数,否则您将使用 qsort (C 语言)或 std::sort 获得更好的性能(在 C++ 中)。

int mystrsort(const void *a, const void *b)
{
    return strcmp(*(const char **)a, *(const char **)b);
}

// later:
qsort(title_arr, sizeof title_arr / sizeof(char *), sizeof(char *), mystrsort);

我不会刺探 std::sort,但它的工作原理大致相同(也许更容易)。**

*请注意,任何喜欢的人都可以随意将这些 Wikipedia 链接更改为 Stack溢出链接。最好链接到SO,我刚刚链接到维基百科,因为我知道如何更快地找到我需要的信息。
**请注意,任何喜欢的人都可以自由添加 std::sort 示例。我只是对 C++ 不够熟悉。

This:

char* title_temp = title_arr[i];

title_arr[j] = title_temp;

Is equivalent to:

title_arr[j] = title_arr[i];

You never swap them, you just copy one to the other. You should add this line:

title_arr[i] = title_arr[j];

In between the two. That way, you'll overwrite [i] with [j], but _temp still holds the old value of [i], so you can copy that value into [j], thus swapping them.

I suppose it's also a time for a lesson on algorithms. Your algorithm is known as a "bubble sort" algorithm. It is known for it's simplicity, but in a realistic setting it is known for it's inefficiency (the technical term is "teh sux", and the real technical term is O(n^2) ("N squared") performance). Some more common (and more efficient) algorithms include Quicksort, merge sort, and Heapsort, among many others. For more about measuring algorithmic scalability, see the article on Big Oh notation.*

But, as vava pointed out in a comment, unless your assignment is to write your own sorting function, you're going to get better performance with qsort (in C) or std::sort (in C++).

int mystrsort(const void *a, const void *b)
{
    return strcmp(*(const char **)a, *(const char **)b);
}

// later:
qsort(title_arr, sizeof title_arr / sizeof(char *), sizeof(char *), mystrsort);

I'm not going to stab at std::sort, but it's going to work about the same (perhaps easier).**

*Note that anyone who likes is free to change these Wikipedia links to Stack Overflow links. It would be better to link to SO, I just linked to Wikipedia because I knew how to find the info I needed faster.
**Note that anyone who likes is free to add a std::sort example. I'm just not sufficiently familiar with C++.

橘虞初梦 2024-09-01 17:59:29

你没有正确交换,这就是它不起作用的原因。

#include <iostream>
#include <algorithm>

int const counter = 4;
char * title_arr[counter] = {
    "d", "c", "b", "a"
};

void sortArrays(){
    for(int i = 0; i < counter; i++){
        for(int j = 0; j < i; j++){
            if(strcmp(title_arr[i], title_arr[j]) < 0){
                char* title_temp = title_arr[i];
                title_arr[i] = title_arr[j];
                title_arr[j] = title_temp;
                //you wouldn't have made that stupid mistake this way.
                //std::swap(title_arr[i], title_arr[j]);
            }
        }
    }
}

int compare(void const * a, void const * b) {
    return strcmp(static_cast<char const *>(a), static_cast<char const *>(b));
}

struct StringLess : public std::binary_function<char const *, char const *, bool> {
    bool operator() (char const * a, char const * b) const {
        return strcmp(a, b) < 0;
    }
};

int main(int argc, char * argv[])
{
    sortArrays();
    //those ones better
//  qsort(title_arr, counter, sizeof(char *), compare);
//  std::sort(title_arr, title_arr + counter, StringLess());
    for (int i = 0; i < counter; i++) {
        std::cout << title_arr[i] << ", ";
    }
    return 0;
}

You didn't swap properly, that's why it didn't work.

#include <iostream>
#include <algorithm>

int const counter = 4;
char * title_arr[counter] = {
    "d", "c", "b", "a"
};

void sortArrays(){
    for(int i = 0; i < counter; i++){
        for(int j = 0; j < i; j++){
            if(strcmp(title_arr[i], title_arr[j]) < 0){
                char* title_temp = title_arr[i];
                title_arr[i] = title_arr[j];
                title_arr[j] = title_temp;
                //you wouldn't have made that stupid mistake this way.
                //std::swap(title_arr[i], title_arr[j]);
            }
        }
    }
}

int compare(void const * a, void const * b) {
    return strcmp(static_cast<char const *>(a), static_cast<char const *>(b));
}

struct StringLess : public std::binary_function<char const *, char const *, bool> {
    bool operator() (char const * a, char const * b) const {
        return strcmp(a, b) < 0;
    }
};

int main(int argc, char * argv[])
{
    sortArrays();
    //those ones better
//  qsort(title_arr, counter, sizeof(char *), compare);
//  std::sort(title_arr, title_arr + counter, StringLess());
    for (int i = 0; i < counter; i++) {
        std::cout << title_arr[i] << ", ";
    }
    return 0;
}
琉璃繁缕 2024-09-01 17:59:29

糟糕的编码风格:
1.不要使用全局变量。最好将数组和长度作为参数传递给排序函数。为什么?你的函数不可重用。如果您需要对另一个数组进行排序怎么办?是的,您需要编写另一个排序函数...
2.更高级的技巧:使用高阶函数的模拟。如果您不仅需要对字符进行排序怎么办?整数、浮点数、字符串或您自己的类型。在这种情况下,您还可以将compare()函数传递到排序函数中,该函数可以比较数组的对象。

Bad coding style:
1. Don't use global variables. It's better to pass your array and length as arguments into sort function. Why? Your function is not reusable. What if you will need to sort another array? Yes, you will need to write another sort function...
2. More advanced tip: use emulation of higher-order function. What if you will need to sort not only characters? Integer, floats, strings or your own types. In this case you can also pass compare() function into your sort function which can compare objects of your array.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文