查找算法之二分搜索
来源:互联网 发布:java flickr api 编辑:程序博客网 时间:2024/05/21 12:49
二分搜索的思路:
二分搜索的前提是需要待搜索的数组是有序的,令A[low…high]为元素按升序排列的非空数组,A[mid]为中间元素,x为给定元素,假定x>A[mid],那么,x肯定在A[mid+1],…,A[high]中,接下来只需在A[mid+1…high]中搜索x即可。类似的,如果x< A[mid],只需在A[low..mid-1]中搜索x。重复此过程,直到找到元素x或者当前数组长度为0为止。
二分搜索的实现:
/** * 二分搜索 * Created by yuzhan on 2017/10/18. */public class main { public static int BinarySearch(int[] A,int x){ int low = 0; int high = A.length-1; int j = 0; while (low <= high){ int mid = (low+high)/2; if(x == A[mid]) { j = mid; break; }else if(x < A[mid]) high = mid - 1; else low = mid + 1; } if(j != 0) return j; else return -1; } public static void main(String[] args) { int[] A = {1,2,3,6,14,23,65,75,134,167,232}; int x = 75; int index = main.BinarySearch(A,x); System.out.print(index); }}
阅读全文
0 0
- 搜索算法之二分查找
- 查找算法之二分搜索
- 搜索算法之二分查找法
- 二分查找算法、折半搜索、二分搜索
- 二分查找(折半搜索)算法
- 搜索算法--二分查找(python)
- 二分查找算法(java)二分搜索
- 搜索算法----二分查找(折半查找)
- 搜索算法-顺序查找和二分查找
- 搜索算法-二分搜索(折半查找)
- 算法之二分查找
- 算法之二分查找
- 算法之二分查找
- 查找算法之二分查找
- 查找算法之二分查找
- 查找算法之二分查找
- 查找算法之二分查找
- 查找算法之二分查找
- HTTP协议
- 用两个栈实现队列
- Intel Parallel Studio XE 2018 1DVD
- [树形DP] Codeforces 856D. Masha and Cactus
- UE4如何制作小地图
- 查找算法之二分搜索
- 冒泡获取整型列表中最大的数
- copyproperties
- 01字典树板子
- tensorflow 调试技巧汇总
- OkHttp+RecyclerView,利用OkHttp请求数据,并RecyclerView展示
- OpenCV轮廓、多边形逼近、关键点、周长和面积、边界框、矩、轮廓树、凹凸包、几何直方图、匹配
- 大型文件下载_特别推荐
- sshpass执行远程脚本