【发布时间】:2020-11-09 03:22:51
【问题描述】:
我正在尝试从头开始创建一个 qsort 函数,该函数对指向结构的指针数组进行排序
这是我现在的代码
static void swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
void _qsort(void* list, int list_len, int left, int right,
int(*comp)(const struct shpg_item *a, const struct shpg_item *b)) {
void *vt, *v3;
int i, last, mid = (left + right) / 2;
if (left >= right)
return;
void* vl = (char*)(list + (left * list_len));
void* vr = (char*)(list + (mid * list_len));
swap(vl, vr);
last = left;
for (i = left + 1; i <= right; i++) {
// vl and vt will have the starting address
// of the elements which will be passed to
// comp function.
vt = (char*)(list + (i * list_len));
if ((*comp)(vl, vt) > 0) {
++last;
v3 = (char*)(list + (last * list_len));
swap(vt, v3);
}
}
v3 = (char*)(list + (last * list_len));
swap(vl, v3);
_qsort(list,list_len, left, last - 1, comp);
trace_int(1);
_qsort(list, list_len, last + 1, right, comp);
}
void list_sort(struct shpg_item **list, int list_len,
int(*comp)(const struct shpg_item *a, const struct shpg_item *b)) {
_qsort(*list,list_len,0,(list_len-1),comp);
}
但这给出了分段错误错误,谁能告诉我为什么并帮助我?
【问题讨论】:
-
或许可以尝试模仿
qsort的签名正是。 -
@n.'pronouns'm。那会是什么?我在网上找遍了,但找不到类似的实现
-
你不是从实现开始的。您从文档开始。标准
qsort函数的签名 是什么?将其用于您自己的功能。 -
我无法理解您的算法,例如您在任何情况下都使用
swap(vl, vr);和swap(vl, v3);,所以如果不先检查元素的顺序是否错误,那是没有意义的。此外,list + (left * list_len)和其他类似的表达式是一个很好的方法,可以以未定义的行为(您的分段错误错误)退出数组,为什么要乘以 list_length ? -
您的
swap函数交换了两个ints。但是由qsort排序的数组不是ints 的数组。因此,将其视为列表数组是未定义行为。 (除了提到的其他问题之外。)
标签: arrays c sorting struct quicksort