简体   繁体   中英

Strange results from custom sort function

I'm trying to create a sort function that takes in a pointer to a dynamically created memory (malloc), the total number of items and the max size of an item.

My current function outputs an alphabetized list, but with the very last result listed in the first position. I cannot for the life of me, understand what is wrong with the code to cause output like this.

int sort_array (char *array, int count, int size)
{
    int i, j;
    char *temp;

    if((temp = malloc((size + 1) * sizeof(char))) == NULL)
    {
        fprintf(stderr, "sort_array: malloc failed\n");
        return(RETURN_FAILURE);
    }

    for (i = 0; i < (count * size); i += size)
        for (j = size; j < (count * size); j += size)
            if (strcmp(&array[i], &array[j]) < 0)
            {
                strcpy(temp, &array[i]);
                strcpy(&array[i], &array[j]);
                strcpy(&array[j], temp);
            }

    return(RETURN_SUCCESS);
}

Output:

Zebra
Alpha
Delta
November
Quasar
Start
Van
Window

main:

int main (int argc, char *argv[])
{
    int x;
    char *data = NULL;
    char *temp = NULL;
    struct dirent *filename;
    char *path = "/testing/i/m";
    int count = 0;
    DIR *dir;

    if((dir = opendir(path)) != NULL)
    {
        while((filename = readdir(dir)) != NULL)
        {
            if(filename->d_name[0] != '.')
            {
                if((temp = realloc(data, (count + 1) * FIELD_SIZE * sizeof(char))) == NULL)
                {
                    free(data);
                    fprintf(stderr, "main: realloc failed\n");
                    exit(EXIT_FAILURE);
                }

                data = temp;
                strcpy(&data[count++ * FIELD_SIZE], filename->d_name);
            }
        }

        closedir(dir);
    }
    else
    {
        fprintf(stderr, "main: unable to read directory contents\n");
        exit(EXIT_FAILURE);
    }

    sort_array(data, count, FIELD_SIZE);

    for(x = 0; x < count; x++)
        printf("%s\n", &data[x * FIELD_SIZE]);

    exit(EXIT_SUCCESS);
}

The inner loop of your sort routine processes too many items, and moreover appears to apply the wrong order. To correctly sort in ascending order, this:

for (i = 0; i < (count * size); i += size)
    for (j = size; j < (count * size); j += size)
        if (strcmp(&array[i], &array[j]) < 0)

should instead be this:

for (i = 0; i < (count * size); i += size)
    for (j = i + size; j < (count * size); j += size)
        if (strcmp(&array[i], &array[j]) > 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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