
递归-C-二分查找+排序
发布日期:2021-05-16 15:22:34
浏览次数:14
分类:精选文章
本文共 2865 字,大约阅读时间需要 9 分钟。
Java 递归二分查找示例 /** * 递归实现二分查找排序算法 * 递归方法寻找有序数组中的目标值,并执行插入操作 * 时间复杂度:O(log n) * @author Administrator */public static void main(String[] args) { int maxSize = 100; // 设置数组最大容量 ordArray arr = new ordArray(maxSize); // 初始化有序数组 arr.insert(72); // 插入数值 arr.insert(62); // 插入数值 arr.insert(90); // 插入数值 arr.insert(45); // 插入数值 arr.insert(65); // 插入数值 arr.insert(76); // 插入数值 arr.insert(78); // 插入数值 arr.insert(23); // 插入数值 arr.insert(45); // 插入数值 arr.insert(56); // 插入数值 arr.insert(67); // 插入数值 arr.insert(456345); // 插入数值 arr.insert(54645); // 插入数值 arr.insert(146); // 插入数值 arr.insert(54465); // 插入数值 arr.display(); // 显示数组内容int searchKey = 45; // 搜索的关键值 if (arr.find(searchKey) != arr.size()) { System.out.println(searchKey); // 输出搜索结果 } else { System.out.println("找不到"); // 输出找不到提示 } }private long[] a; private int nElems; // 数组长度 public ordArray(int max) { // 构造函数初始化数组 a = new long[max]; nElems = 0; }public int size() { // 返回数组当前元素数量 return nElems; }public int find(long searchKey) { // 递归查找函数 return recFind(searchKey, 0, nElems - 1); }private int recFind(long searchKey, int lowerBound, int upperBound) { int curIn = (lowerBound + upperBound) / 2; if (a[curIn] == searchKey) { return curIn; // 返回找到索引位置 } else if (lowerBound > upperBound) { return nElems; // 表示元素未找到 } else { if (a[curIn] < searchKey) { return recFind(searchKey, curIn + 1, upperBound); } else { return recFind(searchKey, lowerBound, curIn - 1); } } }public void insert(long value) { // 插入排序方法 int j; for (j = 0; j < nElems; j++) { if (a[j] > value) { break; // 找到插入位置 } } for (int k = nElems; k > j; k--) { a[k] = a[k - 1]; } a[j] = value; nElems++; }public void display() { // 显示数组内容 for (int j = 0; j < nElems; j++) { System.out.print(a[j] + " "); } System.out.println(); }
发表评论
最新留言
路过,博主的博客真漂亮。。
[***.116.15.85]2025年04月12日 14时37分13秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
FI 替代相关 OSS Note 要点记录
2019-03-17
蓝桥杯---试题 算法提高 欧拉函数(数学)
2019-03-17
【网络加速】TensorRT7-开发指南中文_Plus版【1】
2019-03-17
SaltStack about The Top File 使用知识介绍
2019-03-17
网络协议和支持(一)、uuid模块
2019-03-17
numpy.frombuffer()
2019-03-17
文件结束符EOF
2019-03-17
Latex 错误集合
2019-03-17
Python的内置函数(四十一)、 index()
2019-03-17
Python字符串操作之字符串分割与组合
2019-03-17
tf.tuple
2019-03-17
windows系统配置自动tomcat
2019-03-17
49数据通路的功能和基本结构
2019-03-17
Java面试宝典(2020版)
2019-03-17
Springboot 初學習
2019-03-17
2020年云南省专升本 - 「计算机」专业各院校招生计划
2019-03-17
Android 四大组件、五大存储、六大布局总结
2019-03-17