【Java】二分法查找
2024-09-07 10:26:46
二分法查找
前提:所要查找的数组必须有序
public class Dichotomy {
public static void main(String[] args) {
int[] array = new int[]{-78,-64,-53,-43,-31,-10,-5,0,20,40,62,78,84,96,108};
int dest = -78;
int head = 0;//初始的首索引
int end = array.length - 1;
boolean isFlag = false;
while(head <= end) {
int middle = (head + end ) / 2;//找到中间位置
if(dest == array[middle]) {//比较中间位置的数值与目标数值是否相等
System.out.println("找到了指定元素,位置为:" + middle);
isFlag = true;
break;
}
else if(dest < array[middle]) {//如果目标数值小于中间数值,使尾索引等于中间值减一
end = middle - 1;
}
else if(dest > array[middle]) {//如果目标数值大于中间数值,使首索引等于中间值加一
head = middle + 1;
}
}
if(isFlag == false)
System.out.println("很遗憾,没有找到!");
}
}
最新文章
- iteye上总结的编程精华资源
- thinkphp自定义标签库
- BCB中实现拖拽Panel 改变位置和大小的代码
- C#--参数数组
- [已解决] MyBatis 中bind用法
- asp.net负载均衡方案[转]
- VB程序逆向反汇编常见的函数
- 动作-CCActionInterval之CCGridAction家族
- Jasper_chart_create a new stacked chart
- python修炼4
- Zabbix 3.0 部署监控 [二]
- 原生javascript 的MAP使用
- ArcGIS——使用符号级别区分重叠的面图层
- mpvue——页面跳转
- HTML5服务器消息推送(java版)
- 51nod 1130 N的阶乘的长度 V2(斯特林近似)
- oracle orion hugepages_settings.sh(支持OEL 7,4.1内核)
- 2018.11.04 洛谷P1081 开车旅行(倍增)
- Windows Phone本地数据库(SQLCE):9、Connection Strings(翻译) (转)
- css弹性盒子
热门文章
- mysql表死锁查询
- 使用IDEA开发的java compiler经常会自动变为1.5
- 【LeetCode】1472. 设计浏览器历史记录 Design Browser History (Python)
- 【LeetCode】1461. 检查一个字符串是否包含所有长度为 K 的二进制子串 Check If a String Contains All Binary Codes of Size K
- 【LeetCode】1171. Remove Zero Sum Consecutive Nodes from Linked List 解题报告 (C++)
- 【LeetCode】415. Add Strings 解题报告(Python)
- 【LeetCode】941. Valid Mountain Array 解题报告(Python)
- 【LeetCode】477. Total Hamming Distance 解题报告(Python & C++)
- 1114. Boxes
- Hive SQL优化思路