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 ordern",
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为 as(void **)(指向指针数组的void指针)是不可移植的。它不适用于指向不同类型的指针具有不同表示形式的体系结构。幸运的是,这些架构极为罕见。 - 该
&中&ordered_structures是多余的。 - 该类型的
data_size,i而size在参数sort_array应该是一致的。size_t似乎是更好的选择。 - 排序算法(冒泡排序)对于大型数组效率低下。C 库有一个
qsort函数,它使用更有效的方法,但会采用不同的排序函数(不同的参数和不同的返回值语义)。
- i.e. the more you stare at the prewritten code, the worse it looks. It is actually totally awful.