Billy
Billy

Reputation: 1293

Sort String Array by String Length in C

I have an array of strings in C. These strings store the paths of filesystems that need to be unmounted.

For example...
mountlist[0] = "/proc"
mountlist[1] = "/dev"
mountlist[2] = "/dev/shm"
and so on...

I need to unmount the nested filesystems before the filesystems they are mounted over (so /dev/shm needs to be unmounted before /dev). I was thinking that the easiest way to do this would be to sort the strings by length, longest first. I have the number of strings in the array stored in the integer i.

With the code that I've been able to come up with so far, given that strnum is an integer of the string I need to access, the strings are accessible with mountlist[strnum] and the corresponding length is stored in length[strnum].

In conclusion, how can I sort the strings in array by greatest to least length? I don't need to actually sort the strings, I just need to access them in the right order. I can't figure out how to write it, but I was thinking of code that creates an int array with the number of each string array in the right order (the example above would be {2, 0, 1}), so if that array was named sort then mountlist[sort[0]] would be the longest string. With such an array, the corresponding for loop would be:

for (int q = 0; q < i; q++) {
    umount(mountlist[sort[q]]);
}

Upvotes: 4

Views: 922

Answers (2)

Johnny Johansson
Johnny Johansson

Reputation: 270

If you don't want to depend on anything "external" like qsort, which may or not be available in your environment, this should do it:

for (int j = 0; j < i; ++j) sort[j] = j;

for (int j = 0; j < i - 1; ++j) {
    int longest = j;
    for (int k = j + 1; k < i; ++k) {
        if (length[sort[k]] > length[sort[longest]]) longest = k;
    }
    int tmp = sort[longest];
    sort[longest] = sort[j];
    sort[j] = tmp;
}

Upvotes: 1

Ahmed Agiza
Ahmed Agiza

Reputation: 370

You can just use qsort with a custom comparator:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int cmp(const void *first, const void *second) { 
    const char **firstCast = (const char ** )first;
    const char **secondCast = (const char **) second;
    return strcmp(*secondCast, *firstCast);
}
int main(void) {
    const char *a[3];
    a[0] = "longest";
    a[1] = "short";
    a[2] = "medium";
    qsort(a, 3, sizeof(char *), cmp);
    for (int i = 0 ; i < 3; i++) {
        printf("%s\n", a[i]);
    }
}

Upvotes: 3

Related Questions