二分查找法
来源:互联网 发布:喀秋莎视频剪辑软件 编辑:程序博客网 时间:2024/05/17 08:25
@Author:云都小生
概述
二分算法是一种查找算法,又称折半查找法,是分治思想的具体实现。从一个有序列表中,找到的某个关键字,效率肯定要比遍历法高很多。
遍历法的时间复杂度是O(n),二分查找算法的时间复杂度是O(lgn)。
算法是这样的,给定一个有序数列a {1,2,13,23,55}
如果我们想查找数据23,就先0+a.length/2(折半) = 2;
比较一下a[2] == 23,如果是就返回下标,如果不是就再比较a[2]是否大于23,如果大,我们就从前半段查找,反之则从后半段开始。看图:
代码实现
在看代码之前,请保证你能懂递归思想。
public class Bsearch { public static void main(String[] args){ int[] nums = new int[]{1,3,4,55,66,123}; int date = 1; int index = search(nums,0,nums.length,date); if(index != -1) { System.out.println("查到了,下标是:" + index); } else { System.out.println("数列中没有这个元素!"); } } public static int search(int[] nums,int low,int high,int date) { if(nums.length == 0) //数组为空,防范性编程 { return -1; } if(high<low) //查找到最后,找不到 { return -1; } int center = (low+high)/2; //每次都折半 if(date == nums[center]) { return center; } else if(date < nums[center]) { return search(nums,low,center-1,date); } else { return search(nums,center+1,high,date); } }}
对最好情况的优化
最好的情况就是,数列的第一个元素或者最后一个元素就是要查找的数据。这样,我们就不需要穷举到最后。但是,相应的代码量也会增加。
public class Bsearch { public static void main(String[] args){ int[] nums = new int[]{1,3,4,55,66,123}; int date = 1; int index = search(nums,0,nums.length,date); if(index != -1) { System.out.println("查到了,下标是:" + index); } else { System.out.println("数列中没有这个元素!"); } } public static int search(int[] nums,int low,int high,int date) { if(nums.length == 0) //数组为空,防范性编程 { return -1; } if(high<low) //查找到最后,找不到 { return -1; } if(nums[low] == date) //当查找的数据是第一个元素 { return low; } if(nums[high] == date) //当查找的数据是最后一个元素 { return date; } int center = (low+high)/2; //每次都折半 if(date == nums[center]) { return center; } else if(date < nums[center]) { return search(nums,low,center-1,date); } else { return search(nums,center+1,high,date); } }}
对最好情况的优化
以上,就是二分算法的基本实现,当然还有扩展的。还有一种情况,我们说这是一个有序数组,但是并没有说是正序还是倒序,所以想把这个方法封装起来之前,要先考虑它的可扩展性。
我们可以分成两个不同的方法,一个专门对正序进行查找,另一个是倒序。
2017/10/18 10:05:08 @Author:云都小生
阅读全文
0 0
- 查找----二分查找法
- 二分查找法,查找string
- 二分查找法
- 二分查找法
- 二分查找法
- 二分查找法
- java 二分查找法
- 二分查找法
- 二分查找法
- 二分查找法
- 二分查找法
- java:二分查找法
- C++ 二分查找法
- 二分查找法
- 【二分查找法】
- php二分查找法
- 二分查找法
- 二分查找法
- node.js中Socket.IO的进阶使用技巧
- PAT 1012. 数字分类 (20)
- 第七周项目6-停车场模拟
- iOS开发企业版ipa分发(In-House模式)记录
- eclipse新建tomcat服务
- 二分查找法
- over partition by与group by 的区别
- webpack使用css-loader,style-loader注意
- AI世界:2018年八大趋势
- Spring Data JPA 使用感受
- 查看防火墙是否关
- 第七周项目5-排队看病模拟
- Linux命令
- .gitignore文件