您的位置:首页 > 其它

重新教自己学算法之循环-递归(二)

2015-05-19 20:11 295 查看
今天主要回顾了循环与递归的基本知识,代码如下:

#include <iostream>
using namespace std;

// normally calcluate like this
int calcluate(int m)
{
int count = 0;
// remember keep the legal parameter
if(m < 0)
return -1;
for(int index = 0; index <= m; index++)
count += index;

return count;
}

// calcluate_recursion in recursive algorithm
int calcluate_recursion(int m)
{
if(m < 0)
return -1;
if(m == 0)
return 0;
else
return calcluate_recursion(m - 1) + m;
}

// recursive algorithm in find()
int find(int array[], int length, int value)
{
int index = 0;
if(NULL == array || 0 == length)
return -1;
for(; index < length; index++)
{
if(value == array[index])
return index;
}
return -1;
}

//change to recursive algorithm
int _find(int index, int array[], int length, int value)
{
if(index == length)
return -1;
if(value == array[index])
return index;
return _find(index + 1, array, length, value);
}
int find_recursion(int array[], int length, int value)
{
if(NULL == array || length == 0)
return -1;
return _find(0, array, length, value);
}

int main()
{
int array[10] = {1,2};
cout<<find_recursion(array,10,2)<<endl;
return 0;
}


总结以下几点:

1:递归以前学来觉得复杂,今天了解的更好些,无非是自己调用自己,本质上,循环也是一种递归。

2:上面find_recursion函数将循环查找改成了递归。

3:普通函数这样进行调用:

函数A调用函数B,函数B调用函数C,在堆栈中数据保存如下:

函数A ^

函数B | (地址递减)

函数C | (地址递减)

递归函数也是如此。

4:必须时刻明白数据存在哪块空间中:

static int value = 100;


static修饰的变量属于全局数据

void process()
{
char* point = (char*)malloc(100);
free(point);
}


point属于堆数据,如果没有free操作,其存在也是全局的,不释放的话,会一直存在。

void process()
{
char name[100] = {0};
return;
}


这里的数据是堆栈内部的数据,函数结束后,name地址指向的内存空间会被其他函数使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息