简体   繁体   English

合并Sort C ++实现,无法识别代码中的错误

[英]Merge Sort C++ implementation, Cannot identify the bug in the code

I tried to implement merge sort in C++ using std::vector . 我试图使用std::vector在C ++中实现合并排序。 I don't see any problem in the logic. 我认为逻辑上没有任何问题。 However, when I run the code I get an array that is larger than the original array and unsorted. 但是,当我运行代码时,我得到一个比原始数组大且未排序的数组。 Can anyone tell me what is wrong with my code? 谁能告诉我我的代码有什么问题吗?

void  merge(vector<double>& x,
            vector<double>& y,
            vector<double>& merged )
{
   int sze_x = x.size();
   int sze_y = y.size();
   int i =0, j=0;

   while (i< sze_x && j < sze_y)
   {
      if(x[i] <= y[j])
      {
         merged.push_back(x[i]);
         ++i;
      }
      else
      {
         merged.push_back(y[j]);
         ++j;

      }
   }
   if(i >= sze_x)
   {
      for(int l =j; l != sze_y; l++)
      {
         merged.push_back(y[l]);

      }
   }
   else
   {
      for(int l =i; l != sze_x; l++)
      {
         merged.push_back(x[l]);
      }
   }

}

void split (vector<double> &A, vector<double> &A_1, vector<double> &A_2)
{
   int mid = A.size()/2;
   int sze = A.size();
   for(int i =0; i!=sze;i++)
   {
      if(i<mid) A_1.push_back(A[i]);
      else
         A_2.push_back(A[i]);
   }
}

void merge_sort(vector<double>  &arr)
{
   if(arr.size()>1)
   {
      vector<double> arr1, arr2;
      split(arr,arr1,arr2);
      merge_sort(arr1);
      merge_sort(arr2);
      merge(arr1,arr2,arr);

   }
}

When you call 你打电话时

 merge(arr1,arr2,arr);

arr still has all its original contents. arr仍然具有其所有原始内容。 You don't clear the contents before you call push_back to merged in merge . 在调用push_back mergedmerge之前,您无需清除内容。

Add

arr.clear();

before the above line, or add 在上述行之前,或添加

merged.clear();

in merge before the while statement. while语句之前merge

merged.clear();
while (i< sze_x && j < sze_y)

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

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