在尝试使用递归调用创建这种合并排序算法时,我最终得到了 std::out_of_range 的异常。
我对调试和查找错误原因了解不多。下面我将发布代码(不完整,只有部分)和包含相同代码的源文件(当然是完整版)。
我很乐意听取建议,即使他们没有针对此错误提供任何帮助,所以请随时评论此代码并开我的玩笑:)
https://docs.google.com/file/d/0ByVN9ccAyFY2dkVLN0ZlTWVHZG8/edit
主要功能
int main()
{
vector<int> original; //input vector
input (&original); //write input to vector<int> original
divide(&original); //pass the vector
for(unsigned int i=0;i<original.size();i++)//output the results
cout<<original.at(i);
}
输入功能
int input(vector<int> *inVec) //read all input until non-integer
{
int tmp;
while (cin>>tmp)
inVec->push_back(tmp);
for(unsigned int i=0;i<inVec->size();i++)
cout<<inVec->at(i)<<endl;
}
划分
int divide(vector<int> *original)
{
int origL=original->size();
if(origL>1)
{
vector<int> first; //vectors for holding 2 halfs of "original"
vector<int> second; //
first.assign(original->begin(),original->begin()+origL/2);//1st half of "original"
second.assign(original->begin()+origL/2+1,original->end());//2nd half
divide(&first); //recursive call until "first" and
divide(&second); //"second" include only one number
merge(&first,&second,original);//merge first and second back into one vector
}
}
合并函数
int merge(vector<int> *A,vector<int> *B,vector<int> *original)
{
//clear the original vector. we will use it to store sorted results.
original->erase(original->begin(),original->end());
unsigned int i=0,j=0;
//out the smallest number from A and B into
//original[0] and so on. This makes it a
//sorting algorithm.
for(i=0;i<A->size();i++)
{
if(j<B->size())
if(A->at(i)<=B->at(j))
original->push_back(A->at(i));
else{
original->push_back(B->at(j));
i--;j++;}
}
//the ABOVE loop scans whole vector A or B.
//if there are still uncopied elements in
//the other vector, then we check for them and
//push them into original.
if(j<B->size())
for(i=j;i<B->size();i++)
original->push_back(B->at(i));
if(i<A->size())
for(j=i;j<A->size();j++)
original->push_back(A->at(j));
return EXIT_SUCCESS;
}
EDIT1:对 MERGE 进行了更改,因此现在没有运行时错误。但是,输出不对。如果有人注意到可能导致问题的原因,请告诉我。同时,我将尝试自己找到它。