mergesort算法合并功能不起作用

问题描述

我正在尝试制作自己的版本的mergesort,但是,我对如何按顺序将两个数组合并回单个数组感到困惑。

下面是我的代码,在我尝试运行该程序后,弹出了一些对我来说没有意义的数字,例如776247896 327641 57752310

谁能告诉我我的代码出了什么问题?请赐教。非常感谢。

//nL is the length of left[]
//nR is the length of right[]
//nA is the length of A[]

void merge(int left[],int nL,int right[],int nR,int A[],int nA) {
    int temp[nA];
    
    int i = 0,j = 0,k = 0;
    
    while (i < nL && j < nR) {
        if (left[i] <= right[j]) {
            temp[k++] = left[i++];
        }
        else if (left[i] > right[j]) {
            temp[k++] = right[j++];
        }
    }
    
    while (i == nL && j < nR && k < nA) {
        temp[k++] = right[j++];
    }
    while (j == nR && i < nL && k < nA) {
        temp[k++] = left[i++];
    }
    
    for (int m = 0; m < nA; m++) {
        temp[m] = A[m];
    }
}

int main(void) {
    int left[4] = { 13,22,25,60};
    int right[4] = { 9,11,27,55};
    int sorted[8];
    
    merge(left,4,right,sorted,8);
    
    for (int i = 0; i < 8; i++) {
        printf("%i\n",sorted[i]);
    }
}

解决方法

是否应该撤消?

   temp[m] = A[m];

因此,数组A充满了存储在堆栈中的随机字节。

,

merge函数中的最后循环不会从temp复制回到A,而是相反。它应该更改为:

    for (int m = 0; m < nA; m++) {
        A[m] = temp[m];
    }

还请注意以下说明:

  • 目标数组的长度应为左右数组长度的总和,无需指定。

  • 测试else if (left[i] > right[j])是多余的,应将其删除。

  • 测试while (i == nL && j < nR && k < nA)也是多余的:在第一个循环结束时,i == nLj == nR或两者兼有。您只需编写while (j < nR),下面的循环也可以简化。

这是修改后的版本:

#include <stdio.h>

//nL is the length of left[]
//nR is the length of right[]
//nA is the length of A[]

void merge(int left[],int nL,int right[],int nR,int A[]) {
    int temp[nL + nR];
    
    int i = 0,j = 0,k = 0;
    
    while (i < nL && j < nR) {
        if (left[i] <= right[j]) {
            temp[k++] = left[i++];
        } else {
            temp[k++] = right[j++];
        }
    }
    
    while (i < nL) {
        temp[k++] = left[i++];
    }
    while (j < nR) {
        temp[k++] = right[j++];
    }
    
    for (int m = 0; m < k; m++) {
        A[m] = temp[m];
    }
}

int main(void) {
    int left[4] = { 13,22,25,60};
    int right[4] = { 9,11,27,55};
    int sorted[8];
    
    merge(left,4,right,sorted);
    
    for (int i = 0; i < 8; i++) {
        printf("%i\n",sorted[i]);
    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...