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

最佳答案

看起来您的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;
}

关于c - mergesort的合并功能删除按字母顺序排列的最大输入结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47022372/

10-13 05:22