什么是递归?
自己调用自己
例子:老和尚讲故事
计算阶乘:使用递归(慢,占用内存多,但代码易理解);使用迭代(就是循环)
long jiecheng(int n)
{
if(n==0)
return 1;
else
return n*jiecheng(n-1);
}
long diedai(int n)
{
long result=1;
for(int i=n;i>0;i–)
result=result*i;
return result;
}
折半查找:
迭代的折半查找
int BinarySearch_I(int *a,const int x,const int n)
{
int left=0,right=n-1;
while(left<=right)
{
int middle=(left+right)/2;
if(x<a[middle])
right=middle-1;
else if(x>a[middle])
left=middle+1;
else
return middle;
}
return -1;
}
递归的折半查找
int BinarySearch_R(int *a,const int x,const int left,const int right)
{
if(left<=right)
{
int middle=(left+right)/2;
if(x<a[middle])
return BinarySearch_R(a,x,left,middle-1);
else if(x>a[middle])
return BinarySearch_R(a,x,middle+1,right);
else
return middle;
}
}