首页 > 解决方案 > 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;
}

任何帮助是极大的赞赏

标签: cpointersstructurefunction-pointers

解决方案


您的函数将使用 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 automobileas (void **)(指向指针数组的void指针)是不可移植的。它不适用于指向不同类型的指针具有不同表示的体系结构。幸运的是,这些架构极为罕见。
  • &in&ordered_structures是多余的。
  • 的类型data_size和参数应该是一致的。似乎是更好的选择。isizesort_arraysize_t
  • 排序算法(冒泡排序)对于大型数组效率低下。C 库有一个qsort使用更有效方法的函数,但会采用不同的排序函数(不同的参数和不同的返回值语义)。

推荐阅读