当前位置:网站首页>递归的应用
递归的应用
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;
}
结果:
边栏推荐
- 【全网首发】主线程异常会导致 JVM 退出?
- 2020-11-10
- [AI] action recognition using simple neural network -- Based on coco key points
- Common methods of goframe error handling & use of error codes
- MySQL - index
- 聊聊并发编程的12种业务场景
- ArcGIS point cloud (XYZ) data to DEM
- Teach you to reproduce log4j2 nuclear weapon level vulnerability hand in hand
- ambari2.7.5集成es6.4.2
- mysql - 索引
猜你喜欢

【全网首发】JVM性能问题的自动分析

Nacos configuration management

Online software testing training institutions lemon class and itest AI platform achieves strategic cooperation

字幕文件与视频文件对不上的处理方式

ArcMap creates a constant grid and tessellates it into a new grid

Cityengine 3D pipe modeling tutorial

聊聊并发编程的12种业务场景

MySQL transactions

ArcMap 创建常量栅格并镶嵌至新栅格

Cesium 绑定鼠标事件和移除鼠标事件
随机推荐
Switch user mode, privileged mode, global mode, port mode
2.6.2 内存泄漏
Data visualization
Cesium 绑定鼠标事件和移除鼠标事件
Flex flexible layout
字幕文件与视频文件对不上的处理方式
Nacos配置管理
ArcGIS point cloud (XYZ) data to DEM
数据可视化
Shell脚本配置root免密登录到其他主机
mysql - 索引
OpenDDS的QoS和自定义QoS(校时TimingQosPolicy)
Performance bottleneck finding - Flame graph analysis
GoFrame 错误处理的常用方法&错误码的使用
What is the employment prospect of software testing? There is a large demand for talents and strong job stability
10问10答:你真的了解线程池吗?
ambari集群扩容节点+扩容服务操作
【AI】利用简单神经网络做动作识别——基于coco关键点
Solve the problem of inconsistent prediction effect between text detection training model and information model based on paddleocr
2.6.2 memory leakage