简体   繁体   English

排序结构数组或排序结构C哪个更快?

[英]Which is faster, sorting an array of structs or sorting a list of structures C?

I am faced with a challenge. 我面临挑战。 I have data on a linked list of structs. 我在结构的链表上有数据。 Do l move the data onto an array of structs then sort it using qsort() or do l use merge sort? 我是将数据移动到结构数组上,然后使用qsort()对其进行排序还是使用合并排序? This is the struct: 这是结构:

struct properties{
    char *path;
    char *name;
    char *extension;
    long int size;
    long unsigned created;
    long unsigned modified;
    long unsigned access;
    int permissions;
};

I would create an array of pointers to the structs and sort the pointer array using qsort . 我将创建一个指向结构的指针数组,并使用qsort对指针数组进行排序。 Using pointers instad of copying the entire structs will use less memory. 使用指针instad复制整个结构将占用更少的内存。

Create a comparator like this: 创建一个这样的比较器:

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;
}

Call it like this: 这样称呼它:

 struct property *array;
 /* add code to allocate and create array */
 qsort(array, num_elements, sizeof array, propertyComparator);

Edit: 编辑:

If you want to have a sorted linked list, mergesort is about as fast. 如果您想要一个排序的链表,则mergesort的速度差不多。 Seems it depends on how fragmented the linked list is. 似乎取决于链接列表的碎片程度。 See https://stackoverflow.com/a/1525419/646887 参见https://stackoverflow.com/a/1525419/646887

The reason I prefer qsort is that it is part of the C lib, so I don't have to write and maintain so much code. 我之所以喜欢qsort是因为它是C库的一部分,因此我不必编写和维护太多代码。 And it is always a fast choice. 这始终是一个快速的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM