calgorithmsortingnatural-sort

Natural sort in C - "array of strings, containing numbers and letters"


I am looking for a proven algorithm for production. I did see this example but I'm not finding much else on the web or in books.

i.e. file_10.txt > file_2.txt


Solution

  • I assume you already know the C standard library qsort() function:

    void qsort(void *base,
               size_t nel,
               size_t width,
               int (*compar)(const void *, const void *);
    

    That last parameter is a function pointer, which means you can pass any function to it. You could use strcmp(), in fact, but that would give you ASCIIbetical, and you specifically want a natural sort.

    In that case, you could write one pretty easily:

    #include <ctype.h>
    
    int natural(const char *a, const char *b)
    {
        if(isalpha(*a) && isalpha(*b))
          {
            // compare two letters
          }
        else
          {
            if(isalpha(*a))
              {
                // compare a letter to a digit (or other non-letter)
              }
            else if(isalpha(*b))
              {
                // compare a digit/non-letter to a letter
              }
            else
              {
                // compare two digits/non-letters
              }
          }
    }
    

    Some of the elses could be cleared up if you just return early, but there's a basic structure. Check ctype.h for functions like isalpha() (if a character is part of the alphabet), isdigit(), isspace(), and more.