实现二分法查找——java实现
2015-09-10 00:07
597 查看
java实现二分法查找,前提:要求待查找的数组已经是按照升序排好的。
结果:
0
4
-6
-1
-1
package test; public class test { public static void main(String[] args) { int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79}; int i = BinarySearch.binarySearch(list, 2); // Returns 0 System.out.println(i); int j = BinarySearch.binarySearch(list, 11); // Returns 4 System.out.println(j); int k = BinarySearch.binarySearch(list, 12); // Returns –6 System.out.println(k); int l = BinarySearch.binarySearch(list, 1); // Returns –1 System.out.println(l); int m = BinarySearch.binarySearch(list, 3); // Returns –2 System.out.println(l); } } class BinarySearch { /** Use binary search to find the key in the list */ public static int binarySearch(int[] list, int key) { int low = 0; int high = list.length - 1; while (high >= low) { int mid = (low + high) / 2; if (key < list[mid]) high = mid - 1; else if (key == list[mid]) return mid; else low = mid + 1; } return -low - 1; // Now high < low } }
结果:
0
4
-6
-1
-1
相关文章推荐
- java初学环境变量的配置
- struts2标签库
- Spring+Mybatis+Maven+web整合
- spring事物和hibernate session提交小记
- Java任意同类型对象的复制
- spring 在web容器启动时执行初始化方法
- Spring security整合CAS单点登出的相关配置
- Spring中使用Map、Set、List、数组、属性集合的注入方法配置文件
- eclipse 安装svn插件
- Spring+Mybatis+Maven+web整合
- JAVA基础之多态
- JAVA中的FORMAT
- Eclipse详细设置护眼背景色和字体颜色
- [Java Concurrency in Practice]第十四章 构建自定义的同步工具
- Java 万年历输出方法
- 贪吃蛇java源代码做了一些变动自己改名为“我要变胖”
- springMVC+mybatis+ehcache详细配置
- java的构造函数
- java类加载器-(2)
- 【笔记】Eclipse反编译工具Jad及插件JadClipse配置