合并函数的合并删除最大的按字母顺序排序的条目结构

时间:2017-10-30 18:54:36

标签: c arrays sorting memory allocation

mergesort函数正确排序,直到最后一次迭代,其中最大的字母值从完成的数组中完全删除。我是C的新手,我正在努力解决这个问题,因为mergesort 与ENTRY结构的OCCURRENCES属性完美匹配,但在使用strcmp时没有使用char数组WORDS ...它应该工作同样,这里是结构和合并和排序函数的代码:

这是我输出的示例:文件包含  "你好世界你好吗"

| hello                | 1          |
| world                | 1          |
| how                  | 2          |
| are                  | 1          |
| you                  | 1          |
| doing                | 1          |
+-----------------------------------+

+_____________________________+
| Word          | Occurrences |
+-----------------------------+
| how          | 2            |
| doing        | 1            |
| you          | 1            |
| are          | 1            |
| world        | 1            |
| hello        | 1            |
+-----------------------------+

+___________________________________+
| Word           | Occurrences      |
+-----------------------------------+
| are                  | 1          |
| doing                | 1          |
| hello                | 1          |
| how                  | 2          |
| world                | 1          |
+-----------------------------------+
zoe@zoe-VirtualBox:~/Analysis$ ^C

1 个答案:

答案 0 :(得分:0)

您的merge功能似乎发生了复制/粘贴错误。而不是:

while(l <= high) b[i++] = a[l++];

你想:

while(m <= high) b[i++] = a[m++];

在此之后,您的排序代码工作正常。

这是一些测试代码。我叫它:

./sortTest hello world hello rabbit dog fox hen worm world 01234567890123456789012345678901234567890123456789 01234567890123456789012345678901234567890123456789 ant

输出结果为:

Results ... 
01234567890123456789012345678901234567890123 2
ant 1
dog 1
fox 1
hello 2
hen 1
rabbit 1
world 2
worm 1

这是测试代码:

ENTRY *find_dup(ENTRY* entries, const char *str, int N)
{
    ENTRY *dup = NULL;
    int i;
    for(i=0; i < N; ++i)
    {
        if (strncmp(entries[i].WORD, str, sizeof(entries[i].WORD)-1) == 0)
        {
            dup = entries + i;
            break;
        }
    }
    return dup;
}

void print_entries(const ENTRY* entries, int N)
{
    int i;
    for(i=0; i < N; ++i)
    {
        fprintf(stdout, "%s %d\n", entries[i].WORD, entries[i].OCCURRENCES);
    }
}

int main(int argc, const char **argv)
{
    int i, N=0;
    ENTRY *entries = malloc((argc-1)*sizeof(*entries));
    ENTRY *scratch = malloc((argc-1)*sizeof(*entries));
    for(i=1; i < argc; ++i)
    {
        ENTRY *dup = find_dup(entries, argv[i], N);
        if (dup == NULL)
        {
            strncpy(entries[N].WORD, argv[i], sizeof(entries[N].WORD));
            entries[N].WORD[sizeof(entries[N].WORD)-1] = 0;
            entries[N].OCCURRENCES = 1;
            ++N;
        }
        else
        {
            ++dup->OCCURRENCES;
        }
    }

    sort(entries, scratch, 0, N-1, 0);

    fprintf(stdout, "Results ... \n");
    print_entries(entries, N);    

    free(entries);
    free(scratch);

    return 0;
}