MergeSort更改原始向量的内容

时间:2018-10-16 19:44:25

标签: vector mergesort

我在用Vectors实现合并排序时遇到问题。自从我尝试使用数组并可以正常工作以来,我目前的实现是正确的,但是当我尝试合并向量时,我遇到了问题。我知道我的问题,但是我的解决方案无法正常工作。

Here is the entire code:
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

void print(vector<int> x)
{
  for (int i =0; i<9; i++)
  {
    cout << x[i] << " ";
  }
  cout << endl;
}

void merge(int low, int high, vector<int> x)
{
  int mid = (low+high)/2;
  int leftC = low;
  int rightC = mid+1;
  int tempC = low;
  int arr[9];

  while (leftC <= mid && rightC <= high)
  {
    if(x[leftC] < x[rightC]){
      cout << "LC++Temp: " << x[leftC] << endl;
      arr[tempC++] = x[leftC++];
    }

    else { 
      cout << "RC++Temp: " << x[leftC] << endl;
      arr[tempC++] = x[rightC++];
    }
  }
  if(leftC > mid)
  {
    for (int k =rightC; k<=high; k++)
    {
      cout << "Inserteted: " << x[k] << endl;
      arr[tempC] =  x[k];
      tempC++;
    }
  }
  else {
    for(int k=leftC; k<=mid;k++)
    {
      cout << "Inserteted: " << x[k] << endl;
      arr[tempC] = x[k];
      tempC++;
    }
  }
  cout << "Done cycle" << endl;
  cout << "arr: ";
  for(int k=low;k<=high;k++) {
   cout << arr[k] << " ";

  }
  cout << endl;
  for(int k=low;k<=high;k++) {
   x[k]=arr[k];
  }
  cout << "New x: ";
  print(x);
}

void mergeSort(int low, int high, vector<int> x)
{
  if (high>low)
  {
    int mid = (low+high)/2;
    cout<< "LEFT Merge( " << low << "," << mid << " )" << endl;
    mergeSort(low,mid,x);
    cout<< "RIGHT Merge( " << mid+1 << "," << high << " )" << endl;
    mergeSort(mid+1,high,x);
    cout << "NORMAL merge( " << low << "," << high << " )" << endl;
    merge(low,high,x);
    cout << "Function X: ";
    print(x);
  }
}


void mergeSort(vector<int> x)
{
  int size = 9;
  mergeSort(0,size-1,x);
}

int main() {
  vector<int> x = {10,52,2,5,15,89,56,11,99};
  print(x);
  mergeSort(x);
  print(x);
}

问题出现在这里:

  for(int k=low;k<=high;k++) {
   x[k]=arr[k];
  }
  cout << "New x: ";
  print(x);
}

当我更改其中的内容后,我的x向量保持不变。我尝试将向量作为参考传递,但向量仍返回其原始值 整数而不是新的更新值,这将使我的算法陷入困境。

0 个答案:

没有答案