简体   繁体   English

合并排序无法正常工作?

[英]Merge Sort not working correctly?

void mergeSubArr(int arr[], int lb, int mid, int ub){
    int temp[size], i = lb, j = mid, k = 0;
    while(i<mid && j<=ub){
        if(arr[i] <= arr[j])
            temp[k] = arr[i++];
        else
            temp[k] = arr[j++];
        k++;
    }
    while(i<mid)
        temp[k++] = arr[i++];
    while(j<=ub)
        temp[k++] = arr[j++];

    for(k=0;k<size;k++)
        arr[k] = temp[k];

}

void mergeArr(int num[], int lb, int ub){
    int mid;
    if((ub-lb)>1){
        mid = (lb+ub)/2;
        mergeArr(num, lb, mid);
        mergeArr(num, mid+1, ub);
        mergeSubArr(num, lb, mid+1, ub);
    }
}

when calling the function mergeArr the output is outputting some other elements which are not initially present in the array?当调用函数 mergeArr 时,输出正在输出一些最初不存在于数组中的其他元素? I think there is something wrong with the mergeSubArr function please help me out here in finding a solution.我认为 mergeSubArr 函数有问题,请帮我在这里找到解决方案。

There are basically two things wrong with your algorithm:你的算法基本上有两个问题:

You fill the array temp from index 0 on.您从索引 0 开始填充数组temp Later, you need to copy it to arr , but starting at the lower bound.稍后,您需要将其复制到arr ,但从下限开始。 You also shouldn't copy size elements, because you can't be sure that the original array even has size elements.您也不应该复制size元素,因为您无法确定原始数组是否具有size元素。 (Thanks, BLUEPIXY, for spotting this one.) You should probably also make sure that size is big enough to hold all elements. (感谢 BLUEPIXY 发现这个。)您可能还应该确保size足够大以容纳所有元素。

Your upper bound is inclusive.你的上限是包容性的。 That means that if (ub - lb > 1) catches the case where there are more than two elements.这意味着if (ub - lb > 1)捕捉到有两个以上元素的情况。 You still have to treat the case where there are two elements, which may be in the wrong order, either by making the above condition ub - lb > 0 or by having an else clause where you swap the elements if they are in the wrong order.您仍然必须处理有两个元素可能顺序错误的情况,方法是使上述条件ub - lb > 0或使用 else 子句,如果元素顺序错误,您可以在其中交换元素.

So make these changes:所以做这些改变:

int temp[size], i = lb, j = mid, k = lb;

Start the temp array from the lower bound.从下限开始临时数组。

for(k = lb; k <= ub; k++)
    arr[k] = temp[k];

Copy only the subarray in question.只复制有问题的子数组。

if (ub - lb > 0) ...

Catch the case where there are two elements, too.还要注意有两个元素的情况。

On a personal note, I find the mergesort algorithm much easier when it passes subarrays via pointer arithmetic and length.就个人而言,我发现归并排序算法在通过指针算术和长度传递子数组时要容易得多。 It forgoes much fiddling with offsets.它放弃了对偏移量的大量摆弄。

All are okk.一切都好。 Instead if((ub-lb)>1) Just replace相反if((ub-lb)>1)只需替换

if((ub-lb)>0)

OR或者

if(ub > lb)

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

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