读书人

如何把这个递归转换成循环

发布时间: 2012-03-12 12:45:33 作者: rapoo

怎么把这个递归转换成循环
void MSort(int Left,int Right)
{
int Center;
if(Left<Right)
{
Center = (Left + Right)/2;
MSort(Left,Center);
MSort(Center+1,Right);
Printf("%d %d %d\n",Left,Center+1,Right);
}
}
谢谢达人~

[解决办法]
void MSort(int Left,int Right)
{
stack.push( Left );
stack.push( Right );

while( ! stack.empty() ) {
int r = stack.pop();
int l = stack.pop();
if( l < r ) {
int Center = ( l + r ) / 2;
stack.push( l );
stack.push( Center );
stack.puch( Center + 1 );
stack.puch( r );
Printf("%d %d %d\n",l,Center+1,r);
}
}
}
[解决办法]
如果要求输出结果顺序一样,可以将输出结果保留到另一个vector中最后输出就行了

void MSort(int Left,int Right)
{
Stack stack;

vector< int > result;
stack.push( Left );
stack.push( Right );

while( ! stack.empty() ) {
int r = stack.pop();
int l = stack.pop();
if( l < r ) {
int Center = ( l + r ) / 2;
stack.push( l );
stack.push( Center );
stack.push( Center + 1 );
stack.push( r );
result.push_back( l );
result.push_back( Center );
result.push_back( r );
}
}
int i = result.size() - 1;

while( i > 0 ) {
int r = result[ i-- ];
int center = result[ i-- ];
int l = result[ i-- ];
printf("%d %d %d\n",l,center+1,r);
}

}

读书人网 >C语言

热点推荐