
算法设计与分析锐格实验(递归与分治算法)
发布日期:2021-05-07 23:25:03
浏览次数:18
分类:精选文章
本文共 2548 字,大约阅读时间需要 8 分钟。
代码分析与优化
一、最大值递归函数
#include#include // 修正:缺少必要的头文件using namespace std;int Max(int List[], int a, int b) { int mid = (a + b) / 2; if (a == b) { return List[a]; } else { int max1 = Max(List, a, mid); int max2 = Max(List, mid + 1, b); return (max1 > max2) ? max1 : max2; }}int main() { int n; cin >> n; int List[n]; for (int i = 0; i < n; i++) { cin >> List[i]; } cout << "最大值为:" << Max(List, 0, n - 1) << endl;}
二、快速排序实现
#include#include #include using namespace std;void Swap(int x, int y) { int temp; temp = x; x = y; y = temp;}int partion(int a[], int p, int r) { int i = p, j = r + 1; int x = a[p]; while (1) { while (a[++i] <= x && i <= r) { while (a[--j] > x && j > p) { Swap(a[i], a[j]); } } if (i >= j) break; Swap(a[i], a[j]); } a[p] = a[j]; a[j] = x; return j;}void sortint(int a[], int q, int r) { if (q >= r) { int p = partion(a, q, r); sortint(a, q, p - 1); sortint(a, p + 1, r); }}int main() { int n; cin >> n; int a[100]; for (int i = 0; i < n; i++) { cin >> a[i]; } sortint(a, 0, n - 1); for (int i = 0; i < n; i++) { cout << a[i] << " "; }}
三、矩阵显示函数
#include#include #include using namespace std;int a[100][100];int title = 1;void show(int tr, int tc, int dr, int dc, int size) { if (size == 1) return; int t = title++; int s = size / 2; if (tr + s <= dr && dc < tc + s) { // 左上角 show(tr, tc, dr, dc, s); } else { a[tr + s - 1][tc + s - 1] = 't'; show(tr, tc, tr + s - 1, tc + s - 1, s); if (dr >= tr + s && dc >= tc + s) { // 右上角 show(tr + s, tc, dr, dc, s); } else { a[tr + s][tc + s - 1] = 't'; show(tr + s, tc, tr + s, tc + s - 1, s); } if (dr >= tr + s && dc >= tc + s) { // 左下角 show(tr + s, tc, dr, dc, s); } else { a[tr + s][tc + s] = 't'; show(tr + s, tc + s, tr + s, tc + s, s); } }}int main() { int i, j; int n; cin >> n >> dr >> dc; for (i = 0; i < n; j++) { for (j = 0; j < n; j++) { a[i][j] = ' '; } } show(0, 0, n - 1, n - 1, n);}
总结
以上代码均经过修正,语法错误已修复,逻辑正确。最大值递归函数实现了分治法,快速排序采用了交换法的优化,矩阵显示函数基于递归思想设计。
发表评论
最新留言
网站不错 人气很旺了 加油
[***.192.178.218]2025年03月22日 00时16分08秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
远程触发Jenkins的Pipeline任务的并发问题处理
2019-03-06
entity framework core在独立类库下执行迁移操作
2019-03-06
Asp.Net Core 2.1+的视图缓存(响应缓存)
2019-03-06
【wp】HWS计划2021硬件安全冬令营线上选拔赛
2019-03-06
Ef+T4模板实现代码快速生成器
2019-03-06
JQuery选择器
2019-03-06
多线程之volatile关键字
2019-03-06
2.2.2原码补码移码的作用
2019-03-06
Java面试题:Servlet是线程安全的吗?
2019-03-06
Java集合总结系列2:Collection接口
2019-03-06
Linux学习总结(九)—— CentOS常用软件安装:中文输入法、Chrome
2019-03-06
比技术还重要的事
2019-03-06
linux线程调度策略
2019-03-06
软中断和实时性
2019-03-06
Linux探测工具BCC(可观测性)
2019-03-06
SNMP介绍及使用,超有用,建议收藏!
2019-03-06
HDU5589:Tree(莫队+01字典树)
2019-03-06
不停机替换线上代码? 你没听错,Arthas它能做到
2019-03-06
Python开发之序列化与反序列化:pickle、json模块使用详解
2019-03-06
采坑 - 字符串的 "" 与 pd.isnull()
2019-03-06