简体   繁体   English

合并排序算法运行不正常

[英]Merge sort algorithm is not functioning properly

A merge sorting algorithm is not working as it is supposed to do.合并排序算法无法正常工作。 The output values are not fully sorted in the ascending order. output 值未按升序完全排序。 Some of the values are out of order which is pointing to a bug.有些值乱序,这表明存在错误。

#include <stdio.h>
#include <stdlib.h>

void merge(int *L, int *R, int *a, int nL, int nR) {
    int i, j, k;
    i = j = k = 0;

    while ((i < nL) && (j < nL)) {
        if (L[i] < R[j]) {
            a[k] = L[i];
            ++i;
        } else {
            a[k] = R[j];
            ++j;
        }
        ++k;
    }

    while (i < nL) {
        a[k] = L[i];
        ++i;
        ++k;
    }

    while (j < nR) {
        a[k] = R[j];
        ++j;
        ++k;
    }
}

void mergeSort(int *a, int n) {
    if (n < 2)
        return;

    int i, mid, *L, *R;

    mid = n / 2;

    L = (int *)malloc(mid * sizeof(int));
    R = (int *)malloc((n - mid) * sizeof(int));

    for (i = 0; i < mid; ++i) {
        L[i] = a[i];
    }

    for (i = mid; i < n; ++i) {
        R[i - mid] = a[i];
    }

    mergeSort(L, mid);
    mergeSort(R, n - mid);

    merge(L, R, a, mid, n - mid);

    free(L);
    free(R);
}

int main() {
    int i, n, *a;

    scanf("%d", &n);

    a = (int *)malloc(n * sizeof(int));

    for (i = 0; i < n; ++i) {
        scanf("%d", &a[i]);
    }

    mergeSort(a, n);

    for (i = 0; i < n; ++i) {
        printf("%d ", a[i]);
    }

    free(a);

    return 0;
}

For example, for the following inputs: 10 10 9 8 7 6 5 4 3 2 1例如,对于以下输入: 10 10 9 8 7 6 5 4 3 2 1

I should get these outputs: 1 2 3 4 5 6 7 8 9 10我应该得到这些输出: 1 2 3 4 5 6 7 8 9 10

But the outputs are not in the ascending order.但是输出不是按升序排列的。 The outputs are: 1 3 4 5 2 6 8 9 10 7输出是: 1 3 4 5 2 6 8 9 10 7

Not sure if it covers all the problems but不确定它是否涵盖所有问题,但

while((i < nL) && (j < nL))

should be应该

while((i < nL) && (j < nR))
                        ^
                        note

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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