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
as(void **)
(指向指针数组的void
指针)是不可移植的。它不适用于指向不同类型的指针具有不同表示的体系结构。幸运的是,这些架构极为罕见。 &
in&ordered_structures
是多余的。- 的类型
data_size
和参数应该是一致的。似乎是更好的选择。i
size
sort_array
size_t
- 排序算法(冒泡排序)对于大型数组效率低下。C 库有一个
qsort
使用更有效方法的函数,但会采用不同的排序函数(不同的参数和不同的返回值语义)。
推荐阅读
- php - 记录不存在时显示消息
- sql - 按 ID 和最小/最大日期对二进制变量进行分组
- java - JFormattedTextFields 中的两位数日期
- javascript - CSS网格布局自动调整列和行
- javascript - React + Spring Boot - universall-cookies ,无法设置 httpOnly cookie
- jsonschema - 如何在所需的anyOf jsonSchema中使用anyof?
- javascript - 如何使用打字稿编写一个能够从对象数组中添加或替换元素的函数
- python - 填补时间序列熊猫数据框中的空白
- gantt-chart - 从特定日期开始的 Tableau 甘特条着色
- javascript - 如何使用 JavaScript 固定表格元素