简体   繁体   English

用于合并排序的合并功能

[英]Merging function for merge sort

I am having a difficult time with the merging portion for merge sort. 我在合并部分的合并排序方面遇到了困难。 Every time I merge the two halves of the vector, it ends up losing at least one of the values in the vector. 每次合并向量的两半时,它最终都会丢失向量中的至少一个值。

void merge(vector <double> &v, vector <double> &temp, int start, int size) {
int i, j, k;


i = start;
j = start + size - size/2;
k = start;

temp.resize(v.size());
while(i < start+size/2 && j < start+size) {
    if(v[i] <= v[j]) {
        temp[k] = v[i];
        i++;
        k++;
    //  cout << "i <= j " << temp[k] << endl;
    } else {
        temp[k] = v[j];
        j++;
        k++;
    //  cout << "i > j "<< temp[k] << endl;
    }
}

for(i = start; i < start+size; i++) {
    v[i] = temp[i];
}

} }

Since I don't know the caller implementation and I may be wrong, but I think there are two bugs. 由于我不知道调用方的实现,所以我可能是错的,但是我认为有两个错误。

  • First, i is terminated at start+size/2 in the first while-loop. 首先, i在第一个while循环中以start+size/2终止。 This value must be equal to the first value of j which is start+size-size/2 . 此值必须等于j的第一个值,即start+size-size/2 But, for instance, if size==5 , then start+5/2=start+2 and start+5-5/2=start+3 . 但是,例如,如果size==5 ,则start+5/2=start+2start+5-5/2=start+3 In this case v[start+2] is never entered to the final result. 在这种情况下, v[start+2]永远不会输入到最终结果中。

  • Secondly, after breaking out of the first while-loop, remaining values of v also must be assigned to temp . 其次,在脱离第一个while循环之后,还必须将v剩余值分配给temp

In summary, my quick answer is as follows. 总而言之,我的快速回答如下。 Demo is here . 演示在这里

void merge(std::vector<double> &v, std::vector<double> &temp, int start, int size) 
{
    int i = start;             // left  array begin
    int j = i + size - size/2; // right array begin (which should be guaranteed by caller.)

    int i_max = j;             // left  array end
    int j_max = start+size;    // right array end

    int k = i;
    temp.resize(v.size());

    while(i < i_max && j < j_max) 
    {
        if(v[i] <= v[j]){
            temp[k] = v[i];
            i++;
            k++;
            //std::cout << "i <= j: " << temp[k-1] << std::endl;
        } 
        else {
            temp[k] = v[j];
            j++;
            k++;
            //std::cout << "i >  j: "<< temp[k-1] << std::endl;
        }
    }

    while (i < i_max) { 
        temp[k] = v[i]; 
        i++; 
        k++; 
    } 

    while (j < j_max) { 
        temp[k] = v[j]; 
        j++; 
        k++; 
    } 

    for(i = start; i < j_max; i++) {
        v[i] = temp[i];
    }
}

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

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