二分法查找

前提:所要查找的数组必须有序

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("很遗憾,没有找到!");
}
}

最新文章

  1. iteye上总结的编程精华资源
  2. thinkphp自定义标签库
  3. BCB中实现拖拽Panel 改变位置和大小的代码
  4. C#--参数数组
  5. [已解决] MyBatis 中bind用法
  6. asp.net负载均衡方案[转]
  7. VB程序逆向反汇编常见的函数
  8. 动作-CCActionInterval之CCGridAction家族
  9. Jasper_chart_create a new stacked chart
  10. python修炼4
  11. Zabbix 3.0 部署监控 [二]
  12. 原生javascript 的MAP使用
  13. ArcGIS——使用符号级别区分重叠的面图层
  14. mpvue——页面跳转
  15. HTML5服务器消息推送(java版)
  16. 51nod 1130 N的阶乘的长度 V2(斯特林近似)
  17. oracle orion hugepages_settings.sh(支持OEL 7,4.1内核)
  18. 2018.11.04 洛谷P1081 开车旅行(倍增)
  19. Windows Phone本地数据库(SQLCE):9、Connection Strings(翻译) (转)
  20. css弹性盒子

热门文章

  1. mysql表死锁查询
  2. 使用IDEA开发的java compiler经常会自动变为1.5
  3. 【LeetCode】1472. 设计浏览器历史记录 Design Browser History (Python)
  4. 【LeetCode】1461. 检查一个字符串是否包含所有长度为 K 的二进制子串 Check If a String Contains All Binary Codes of Size K
  5. 【LeetCode】1171. Remove Zero Sum Consecutive Nodes from Linked List 解题报告 (C++)
  6. 【LeetCode】415. Add Strings 解题报告(Python)
  7. 【LeetCode】941. Valid Mountain Array 解题报告(Python)
  8. 【LeetCode】477. Total Hamming Distance 解题报告(Python & C++)
  9. 1114. Boxes
  10. Hive SQL优化思路