我的合并排序算法出了什么问题?

时间:2019-04-28 21:46:16

标签: c++ recursion vector merge mergesort

我的原始向量有{777,7483,3734,6627,7789,8673},然后temp继续对向量进行排序,但是我通过gdb注意到,我的温度在几次之后就将一些数字复制到向量上逐步执行,我的温度向量具有元素{0,3734,7483,3734,6627,0}。因此,我知道有一个复制错误,它需要一个v []元素并将其两次放入temp。我知道排序算法有效,因为当我打印出临时矢量时,即使元素不相同,它也会被排序。最终温度向量具有{777,3734,3734,3734,3734,7483}。它确实可以排序,但是有一个复制错误,我不确定如何修复或如何解决它

int

main (int argc, char* argv[])

{

  size_t n = vectorSize();

  vector<int> vect(n);

    std::random_device sd;

    std::mt19937 mt(sd());

    std::uniform_int_distribution<int> dist (0, 9999);

    for (size_t i = 0; i < n; ++i)

    {

              vect[i] = dist(mt);

    }

    mergeSort(vect);

    cout << "Merge time: " << ms << endl;

    //cout << "Merge compares: " << numCompares << endl;

   vector<int> ACopy(vect);

  std::sort(ACopy.begin(), ACopy.end());

  if(vect == ACopy)
  {

    cout << "Merge ok?     true" << endl;

  }

  else
  {

    cout << "Merge ok?      false" << endl;

  }

  return EXIT_SUCCESS;

}

/************************************************************/

size_t 
mergeSortH(vector<int>& v, vector<int>& temp, size_t first, size_t last)
{

    if (last - first > 1)
    {
        size_t mid = first+(last-first) / 2;
        mergeSortH(v, temp, first, mid);
        mergeSortH(v, temp, mid, last);
        outplaceMerge(v, temp, first, mid, last);
    }
  return 0;
}

/************************************************************/

size_t

outplaceMerge(vector<int>& v, vector<int>& temp, size_t first, size_t mid, size_t last)

{

  size_t numCompares = 0;

  size_t i1 = first;

  size_t i2 = mid;

  size_t i3 = first;

  while((i1 < mid) && (i2 < last))

  { 

    //check if first is less than mid

    if(v[i1] < v[i2])

    {

      temp[i3] = v[i1];//swap

      ++i1;

      ++i3;

      ++numCompares;

    }else{

      temp[i3] = v[i2];//swap

      ++i2;

      ++i3;

      ++numCompares;

    }

  }

  //while first half is less than mid

  while(i1 <=  mid)

  {

    temp[i3] = v[i1];

    ++i1;

    ++i3;

    ++numCompares;

  }

  //while second half is less than last

  while(i2 <= last)

  {

    temp[i3] = v[i2];

    ++i3;

    ++i2;

    ++numCompares;

  }

  //copy elements back into original vector

  for(i1 = first; i1 < i3; ++i1)

  {

    v[i1] = temp[i1];

  }

  cout << temp[i3] << endl;

    return numCompares;

}


/************************************************************/

size_t
mergeSort(vector<int>& v)
{

   vector<int> temp(v.size());

    return mergeSortH(v, temp, 0, v.size());

}

温度向量应吸收原始向量中的所有元素,并将它们分类为温度向量。然后,当对温度向量进行排序时,它将按顺序从温度向量中复制所有元素。原始向量= {777,7483,3734,6627,7789,8673}然后排序并合并为temp,因此temp应该等于{777,3734,6627,7483,7789,8673},然后将这些元素放回v [ ]。标准排序(将始终进行排序)应等于合并排序向量,然后,如果向量= Acopy,它的cout语句将显示true或false。

1 个答案:

答案 0 :(得分:0)

在合并中,两个while应该使用<而不<=:

    // ...
    while(i1 <  mid)
    // ...
    while(i2 < last)
    // ...

您可能希望将last的名称更改为end,因为它是last元素的1 +索引,与std :: vector :: end()相同。