这个合并排序代码有什么问题?

时间:2016-03-28 02:35:37

标签: c++ algorithm pointers iterator mergesort

我正在尝试使用迭代器编写合并排序来教自己c ++,但由于某种原因,这段代码正在编译,但结果没有排序。有人能弄清楚它有什么问题吗?我的未经训练的眼睛似乎完全没问题。

typedef vector<int> vec_int;
typedef vector<int>::iterator vec_int_iter;

void merge_sort(vec_int& vec, vec_int_iter low, vec_int_iter high){
   if(low < high){
      vec_int_iter med = low + (high-low)/2 ;
      merge_sort(vec, low, med);
      merge_sort(vec, med+1, high);
      arrange(vec, low, med, high);
      }
}

void arrange(vec_int& vec, vec_int_iter low, vec_int_iter med, vec_int_iter high){
   vec_int_iter left = low, right = med+1;
   vec_int temp;
   temp.clear();
   vec_int_iter it = temp.begin();

   while(left <= med and right <= high)
      temp.push_back( (*left < *right)? *left++ : *right++ );
   while(left <= med)
      temp.push_back( *left++ );
   while(right <= high)
      temp.push_back( *right++ );

   vec = temp;
}

1 个答案:

答案 0 :(得分:2)

错误的代码是vec = temp,它将在合并的某个步骤中用临时向量替换原始向量。因为,每个排列,temp只是从原始向量的低到高 然后原始向量成为子向量。

您可以每次都返回一个新的向量,或者in place

示例代码,更改排列功能:

  void arrange(vec_int& vec, vec_int_iter low, vec_int_iter med, vec_int_iter high){
     vec_int_iter left = low, right = med+1;
     vec_int temp;
     temp.clear();
     while(left <= med and right <= high)
        temp.push_back( (*left < *right)? *left++ : *right++ );
     while(left <= med)
        temp.push_back( *left++ );
     while(right <= high)
        temp.push_back( *right++ );

     vec_int_iter start = low;
     for(vec_int_iter t = temp.begin(); t <temp.end(); t++){
        *start++ = *t;
     }   
  }