微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C 中结构的通用排序函数

如何解决C 中结构的通用排序函数

所以我有这个问题。我应该创建一些排序函数以在 C 中的通用排序例程中使用。我只有一个函数可以工作。该函数应该用作结构的排序函数代码应按年份排列列表。

这是两个预先编写并用于排序例程的辅助函数代码

static
void swap(void **left,void **right) {
    void *temp = *left;
    *left = *right;
    *right = temp;
}

void sort_array(void *Array[],unsigned size,int (*ordered)(void *,void *))
{
    int i;
    int have_swapped = 1;

    while (have_swapped) {
        have_swapped = 0;
        for (i = 0; i < size - 1; ++i ){
            if (ordered(Array[i],Array[i+1])) {
                swap(&Array[i],&Array[i+1]);
                have_swapped = 1;
            }
        }
    }
}

然后就是这个函数,也是预先写在main里面用来测试的。

int main() {
    int i;
    int status = EXIT_SUCCESS;

    sort_array((void**)data,data_size,&ordered_structures);

    for (i = 0; i < data_size - 1; ++i) {
        if (data[i]->year > data[i+1]->year) {
            fprintf(stderr,"\"%s\" and \"%s\" are out of order\n",data[i]->name,data[i+1]->name);
            status = EXIT_FAILURE;
        }
    }

    return status;
}

结构简单。

struct automobile {
    const char *name;
    unsigned year;
    unsigned price;
};

所以这些是使用的辅助函数。我所要做的就是编写一个函数,该函数将用于使用这些辅助函数对结构进行排序。

我的解决方案可以编译,但是没有达到预期的结果,我的解决方案仍然出现故障。这是我所拥有的。

int ordered_structures(void *left,void *right) {
     const int *x = left;
     const int *y = right;
     if (x < y)
         return 0;
     else 
         return 1;
}

非常感谢任何帮助

解决方法

将使用 2 个指向 struct automobile 对象的指针调用您的函数,您应该比较这些对象的 year 成员:

// return true if swapping should occur. ie: if automobile structures
// are not ordered by their year member (name is inconsistent with semantics)
int ordered_structures(void *left,void *right) {
     const struct automobile *x = left;
     const struct automobile *y = right;
     return (x->year > y->year);
}

注意这些注释:

  • 名称ordered_structures 与预期的语义不一致:如果应该交换指针,即如果对象有序,则返回true。
  • 将指向 struct automobile 的指针数组转换为 (void **)(指向 void 指针数组的指针)是不可移植的。它不适用于指向不同类型的指针具有不同表示形式的体系结构。幸运的是,这些架构极为罕见。
  • & 中的 &ordered_structures 是多余的。
  • data_sizeisize 中的 sort_array 参数的类型应该一致。 size_t 似乎是更好的选择。
  • 排序算法(冒泡排序)对于大型数组效率低下。 C 库有一个 qsort 函数,该函数使用更高效的方法,但会采用不同的排序函数(不同的参数和不同的返回值语义)。
,

您只是在比较指针,而不是它们指向的对象中的值。

使用

if (*x < *y) {
    return 0;
}
else {
    return 1;
}

顺便说一下,因为比较运算符do返回一个布尔值,你可以只写

return *x >= *y;

但你说的是这些

struct automobile {...}

然后您需要将指针转换为 struct automobile * 并比较其中的成员,所以我想也许

const struct automobile *x = left;
const struct automobile *y = right;
return x->price > y->price;

按价格升序排序...和

const struct automobile *x = left;
const struct automobile *y = right;
return x->year > y->year;

对于上升的年份...


附言预先编写的代码看起来非常糟糕,从 (void **) 类型转换开始,这是不正确的 - 即如果该转换是需要来编译,那么代码是错误的,如果不是需要 那么为什么它首先存在。而排序算法是冒泡排序,也就是所谓的“通用坏排序算法”...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。