递归

来源:互联网 发布:北京工商大学网络 编辑:程序博客网 时间:2024/05/17 04:14

递归是很基本的算法,它体现了分而治之的思想。每次递归调用都意味着部分数值要压入栈中(系统维护了一个下压栈),这是跟迭代的区别,因为在迭代中每次循环结束时所有局部变量都获得了释放。所以使用递归算法必须考虑它的深度,考虑是否会造成栈溢出,与及对效率造成的影响。
每一次递归调用,问题的规模都应该有所减少,并最终达到终止条件的要求,从而结束递归调用。
树和链表都是递归定义。
递归是自顶向下的算法。
递归理论上的正确性需要数据归纳法的证明。
用递归计算阶乘是错误的做法。

 

下面是用递归求最大最小值的简单例子:

#include <iostream>
using namespace std;

template<typename T>
void max_min( T a[], int low, int high, T & max, T & min)
{
 if ( low == high )  // 只有一个元素不再划分
 {
  max = min = a[low];
  return;
 }
 else if ( low == high -1 )  // 只有两上元素不再划分
 {
  if ( a[low] < a[high] )
  {
   max = a[high];
   min = a[low];
  }
  else
  {
   max = a[low];
   min = a[high];
  }
  return;
 }

 int mid = (low + high) / 2;
 T  max_another;
 T  min_another;
 max_min( a, low, mid, max, min );  // 不可避免的是栈空间的浪费
 max_min( a, mid+1, high, max_another, min_another );

 if ( max < max_another )
  max = max_another;
 if ( min > min_another )
  min = min_another;
}

int _tmain(int argc, _TCHAR* argv[])
{
 double a[5] = {23.23, 23.45, .3, -89.3, -2.1};
 double max, min;
 max_min<double>( a, 0, 4, max, min );
 cout << "max: " << max << " min: " << min << endl;

 return 1;
}

// 直接比较的一个函数:
// 最少比较n-1次,最多比较2*(n-1)次
template<typename T>
void straight_max_min( T a[], int n, T & max, T & min )
{
 max = min = a[0];
 for ( int nPos = 1; nPos < n; nPos ++)
 {
  if ( a[nPos] > max )
   max = a[nPos];
  else if ( a[nPos] < min )
   min = a[nPos];
 }
}

// 递归的另一个函数写法,求最大值
template<typename T>
T max_in_array( T items[], int low, int high )
{
 if ( low == high )
  return items[low];

 int mid = ( low + high ) / 2;
 T left_max = max_in_array( items, low, mid );
 T right_max = max_in_array( items, low + 1, high );
 if ( left_max > right_max )
  return left_max;
 else
  return right_max;
}