2

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? 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;
};
7
  • How you represent "list" in your code? Is it "array" vs. "list" or "qsort" vs. "merge sort" ? Commented Jun 16, 2015 at 10:47
  • Will you please clear it with an example?? Commented Jun 16, 2015 at 10:47
  • Do you know how to sort a structure?? How can you move char, long int data on a single array?? It's not possible. Commented Jun 16, 2015 at 10:52
  • 2
    The best way to do this is perhaps to implement the linked list as an array, instead of a fully dynamic list. Then sorting becomes trivial. Alternatively, you could consider integrating the linked list with a pointer-based lookup table, so that each item in the linked list can get an index. Commented Jun 16, 2015 at 11:05
  • qsort() available in C can sort an array. It only needs you to specify the sort criterion to be used. You write a comparator function and provide its pointer to qsort(). Commented Jun 16, 2015 at 11:09

1 Answer 1

3

I would create an array of pointers to the structs and sort the pointer array using qsort. Using pointers instad of copying the entire structs will use less memory.

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. Seems it depends on how fragmented the linked list is. See 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. And it is always a fast choice.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you all for your answers. Klas Lindbäck your answer is very informative. Does it mean that l traverse all the elements of the list and get the pointer to each element storing them in the array?
Yes. And if you don't know the size you need to traverse it twice. First to calculate the size and then to collect the pointers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.