Search code examples
csortingbooleancommand-line-argumentsbubble-sort

What The variable find exactly is doing here?


This a program to compare arguments and sorts them lexicographically. Can you please explain what find is doing there and how it affects the code? I see this kind of model in a lot of code; its value varies between 1 and 0 in the while, so can you clarify please.

int main(int argc, char **argv)
{
    char *tmp;
    int find;
    int i;

    find = 1;
    while (find)
    {
        find = 0;
        i = 0;
        while (++i < argc - 1)
        {
            if (strcmp(argv[i], argv[i + 1]) > 0)
            {
                tmp = argv[i];
                argv[i] = argv[i + 1];
                argv[i + 1] = tmp;
                find = 1;
            }
        }
    }
    i = 0;
    while (++i < argc)
        printf("%s\n", argv[i]);
    return (0);
}

Solution

  • This code snippet

    find = 1;
    while (find)
    {
        find = 0;
        i = 0;
        while (++i < argc - 1)
        {
            if (strcmp(argv[i], argv[i + 1]) > 0)
            {
                tmp = argv[i];
                argv[i] = argv[i + 1];
                argv[i + 1] = tmp;
                find = 1;
            }
        }
    }
    

    implements the bubble sort algorithm.

    Initially, it is supposed that command line arguments are not sorted as strings.

    find = 1;
    

    Then within the while loop, the flag find is reset to 0.

        find = 0;
    

    If within the inner while loop

    while (++i < argc - 1)
    {
            if (strcmp(argv[i], argv[i + 1]) > 0)
            {
                tmp = argv[i];
                argv[i] = argv[i + 1];
                argv[i + 1] = tmp;
                find = 1;
            }
    }
    

    there is found an argument (string) that is greater than the next argument (string)

            if (strcmp(argv[i], argv[i + 1]) > 0)
    

    then the adjacent arguments are swapped and the flag find is set to 1 that signals that the array of arguments is not yet sorted (we need at least one more iteration of the outer while loop to check whether all arguments are indeed sorted after this swapping).