排序结构数组或排序结构列表C,哪个更快?
我面临着一个挑战。我有一个结构链表上的数据。我是将数据移动到结构数组中,然后使用qsort()对其排序,还是使用合并排序? 这是结构:排序结构数组或排序结构列表C,哪个更快?,c,arrays,list,sorting,C,Arrays,List,Sorting,我面临着一个挑战。我有一个结构链表上的数据。我是将数据移动到结构数组中,然后使用qsort()对其排序,还是使用合并排序? 这是结构: struct properties{ char *path; char *name; char *extension; long int size; long unsigned created; long unsigned modified; long unsigned access; int pe
struct properties{
char *path;
char *name;
char *extension;
long int size;
long unsigned created;
long unsigned modified;
long unsigned access;
int permissions;
};
我将创建一个指向结构的指针数组,并使用
qsort
对指针数组进行排序。使用指针复制整个结构将使用更少的内存
创建一个比较器,如下所示:
int propertyComparator(const void *s1, const void* s2) {
struct property *p1 = (struct property *)s1, *p2 = (struct property *)s2;
/* compare p1 and p2, below is just an example */
int result = strcmp(p1->name, p2->name);
return result;
}
struct property *array;
/* add code to allocate and create array */
qsort(array, num_elements, sizeof array, propertyComparator);
可以这样称呼:
int propertyComparator(const void *s1, const void* s2) {
struct property *p1 = (struct property *)s1, *p2 = (struct property *)s2;
/* compare p1 and p2, below is just an example */
int result = strcmp(p1->name, p2->name);
return result;
}
struct property *array;
/* add code to allocate and create array */
qsort(array, num_elements, sizeof array, propertyComparator);
编辑:
如果您想要有一个排序的链表,mergesort也差不多一样快。似乎这取决于链表的支离破碎程度。
看
我之所以喜欢
qsort
,是因为它是C库的一部分,所以我不必编写和维护这么多代码。而且它总是一个快速的选择。您如何在代码中表示“列表”?它是“数组”对“列表”还是“qsort”对“合并排序”?请用一个例子来澄清它??你知道如何对结构排序吗??如何在单个数组上移动字符、长整型数据??这是不可能的,最好的方法可能是将链表实现为一个数组,而不是一个完全动态的列表。然后排序就变得微不足道了。或者,您可以考虑将链表与基于指针的查找表集成,以便链表中的每个项都可以得到一个索引。qScTo()在C中可用,可以对数组排序。它只需要您指定要使用的排序标准。您编写了一个比较器函数,并提供了指向qsort()的指针。谢谢大家的回答。克拉斯·林德贝克:你的回答非常翔实。这是否意味着我遍历列表中的所有元素并获取指向数组中存储它们的每个元素的指针?是的。如果你不知道它的大小,你需要遍历它两次。首先计算大小,然后收集指针。