我正在尝试执行此多重递归合并的迭代版本:
我只需要对此类函数进行迭代:
template<class T> deque<T> mergesort<T>::sort(deque<T> &right){
int size = right.size();
if (size <= 1){
return right;
}
int middle = size/2;
deque<T> left;
for(int i = 0; i < middle; i++){
left.push_back(right.front());
right.pop_front();
}
left = sort(left);
right = sort(right);
return merge(left, right);
}
合并功能可以是相同的:
template<class T> deque<T> mergesort<T>::merge(deque<T> &left, deque<T> &right){
deque<T> result;
while(left.size() > 0 || right.size() > 0){
if (left.size() > 0 && right.size() > 0){
if (getOrder(left.front(),right.front())){
result.push_back(left.front());
left.pop_front();
}
else{
result.push_back(right.front());
right.pop_front();
}
}
else if(left.size() > 0){
result.push_back(left.front());
left.pop_front();
}
else if(right.size() > 0){
result.push_back(right.front());
right.pop_front();
}
}
return result;
}
我很难将多个递归函数转换为迭代函数。
感谢每一位亲切的问候。