自定义排序功能导致奇怪的结果

时间:2015-04-09 17:45:29

标签: c linux sorting

我正在尝试创建一个排序函数,该函数接收指向动态创建的内存(malloc)的指针,项目总数和项目的最大大小。

我的当前函数输出按字母顺序排列的列表,但最后一个结果列在第一个位置。我不能为我的生活,理解代码导致输出的错误。

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);
}

输出:

Zebra
Alpha
Delta
November
Quasar
Start
Van
Window

主:

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);
}

1 个答案:

答案 0 :(得分:2)

排序例程的内部循环处理的项目太多,而且似乎应用了错误的顺序。要按升序正确排序,请执行以下操作:

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

应该是这样的:

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