当前位置: 首页 > news >正文

C语言编程--递归程序--求数组的最大元素值

任务:Finding the maximum among N N N items stored in an array a [ 0 ] a[0] a[0], … \ldots , a [ N − 1 ] a[N - 1] a[N1].

实现:

#include <stdio.h>
typedef char Item;Item max(Item a[], int l, int r);Item max2(Item a[], int N);int main(int argc, char** argv){
Item a[] = {'T', 'I', 'N', 'Y', 'E', 'X', 'A', 'M', 'P', 'L', 'E'};Item maxNum = max2(a, 11);printf("%c\n", maxNum);return 0;
}/*** Program 5.6 Divide-and-conquer to find the maximum* -------------------------------------------------------------------------------------------------* This function divides a file a[l],. . . , a[r] into a[l],. . . , a[m] and a[m+1],. . . , a[r],* finds the maximum elements in the two parts (recursively), and * returns the larger of the two as the maximum element in the whole file. * It assumes that Item is a first-class type for which > is defined.* If the file size is even, the two parts are equal in size; * if the file size is odd, the size of the first part is 1 greater than the size of the second part.*/
Item max(Item a[], int l, int r){if (l == r) {return a[l];}Item u, v;int m = (l+r)/2;u = max(a, l, m);v = max(a, m+1, r);if (u > v) {return u;}else {return v;}}Item max2(Item a[], int N){// Item t = a[0];// int i;// for (i = 1; i < N; i++) {//     if (a[i] > t) {//         t = a[i];//     }// }// return t;return max(a, 0, N-1);
}

示例程序5.6的递归分析示意图
示例程序5.6的递归分析示意图

递归调用树结构表示
递归调用树

  • 后续遍历就是调用顺序加返回顺序

C语言编程环境支持示例递归计算的内部栈内容
示例程序在运行时的内部栈内容

http://www.dtcms.com/a/175177.html

相关文章:

  • Java后端开发day42--IO流(二)--字符集字符流
  • 2025年渗透测试面试题总结-某战队红队实习面经(附回答)(题目+回答)
  • Nmap 工具的详细使用教程
  • 《Python星球日记》第34天:Web 安全基础
  • 前端流行框架Vue3教程:13. 组件传递数据_Props
  • 今年我国已发生三级以上地震318次
  • 在 Win11 下安装 Wireshark 的详细步骤
  • 深入浅出iOS性能优化:打造极致用户体验的实战指南
  • 餐饮加盟店如何通过日事清全流程闭环管理实现进度同步与效率升级?
  • Java学习手册:Base64 编码概念和应用场景
  • python校园二手交易管理系统-闲置物品交易系统
  • python setup.py install --user和pip install -e .的区别
  • C++ - 仿 RabbitMQ 实现消息队列(1)(环境搭建)
  • 高等数学第四章---不定积分(4.4有理函数的不定积分2)
  • springBoot中自定义一个validation注解,实现指定枚举值校验
  • 【JEECG】BasicTable单元格编辑,插槽添加下拉组件样式错位
  • 【Trea】Trea国际版|海外版下载
  • Suno v4.5:AI 音乐创作的新突破
  • SLAM:正定矩阵二次型的定义和性质
  • GD32/STM32 ADC/DMA使用指南
  • 人工智能端侧热度再起
  • hybird接口配置
  • FTPS和SFTP(文件传输安全协议)
  • ProteinTools辅助探索蛋白稳定性、动态调控以及结构关系
  • windows操作系统开机自启(自动启动) 运行窗口 shell:startup 指令调出开机自启文件夹
  • mux-vlan基础配置
  • Linux服务之nginx中http设置及虚拟主机搭建
  • day 13 不平衡数据集的处理
  • ctfshow web入门 web52
  • 【coze】记忆体(变量、数据库、长期记忆、消息盒子)