当前位置:网站首页>递归的应用
递归的应用
2022-07-17 05:08:00 【学会放下ta】
递归
函数递归就是函数调用自己,要设置退出条件,否则会一直运行直到耗尽内存空间
递归的应用1
汉诺塔
贴一下用python写的汉诺塔代码,思想是一致的,聪明的你肯定会把他写成C语言的代码吧,所以我就不贴代码咯。
汉诺塔代码实现
递归的应用2
快速排序
基本思想:分而治之
找一个基准数值(随便定一个,习惯是数组中间那个数),分别从左到右寻找大于基准点的数(i是下标)和从右到左寻找小于基准点的数(j是下标),然后令两个数互换,当i超过j时退出循环,此时数组分为两段,左边全部比右边小,然后对两端数组进行递归直到各数组都只有一个元素。
测试代码:
void quick_sort(int array[],int left,int right);
void quick_sort(int array[],int left,int right)
{
int i = left,j = right;//遍历数组
int temp;//互换的基石
int qovit;//选择的基准值
qovit = array[(left + right)/2];
while(i<=j)//遍历一遍数组
{
while(array[i]<qovit)//选择左侧大于基准值的数就跳出循环
{
i++;
}
while(array[j]>qovit)//选择右侧大于基准值的数就跳出循环
{
j--;
}
if(i<j)//交换上面选出的两个数
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;//这里注意交换后要更改指标的值,否则出不去循环,别问我怎么知道的
j--;
}
}
if(left<j)
{
quick_sort(array,left,j);//对左侧递归调用快速排序
}
if(i<right)
{
quick_sort(array,i,right);//对右侧递归调用快速排序
}
}
int main(void)
{
int array[]={
111, 21, 32, 55, 2, 543, 520, 11, 23, 88};
int length = sizeof(array) / sizeof(array[0]);
quick_sort(array,0,length-1);
printf("排序后的结果是:");
for(int i=0;i < length;i++)
{
printf("%d ",array[i]);
}
return 0;
}
结果:
边栏推荐
猜你喜欢
随机推荐
Rxjs source code analysis (I) observable
H5 page uses JS to generate QR code
UML(用例图,类图,对象图,包图)
What are the B domain, m domain and O domain
指针进阶简单总结
MySQL安装配置教程(超级详细)
MySQL transactions
Redis 源码分析-数据结构及实现(字典dict)
Talk about the 8 pits of redis distributed lock
SQL注入
Usage and examples of vlookup function
Excel计算本月剩余天数
MySQL installation and configuration tutorial (super detailed)
ambari 2.7.5集成安装hue 4.6
Switch user mode, privileged mode, global mode, port mode
Excel calculates the remaining days of the month
MySQL cache strategy and solution
Pat class B 1002: write this number
Addition and removal of cesium geojson data
2020-10-22








