二分查找算法
来源:互联网 发布:wp8.1软件 编辑:程序博客网 时间:2024/04/30 12:36
二分查找算法(JAVA)
1.二分查找又称折半查找,它是一种效率较高的查找方法。
2.二分查找要求:(1)必须采用顺序存储结构 (2).必须按关键字大小有序排列
3.原理:将数组分为三部分,依次是中值(所谓的中值就是数组中间位置的那个值)前,中值,中值后;将要查找的值和数组的中值进行比较,若小于中值则在中值前 面找,若大于中值则在中值后面找,等于中值时直接返回。然后依次是一个递归过程,将前半部分或者后半部分继续分解为三部分。
4.实现:二分查找的实现用递归和循环两种方式
5.代码:
1 package other; 2 3 public class BinarySearch { 4 /* 5 * 循环实现二分查找算法arr 已排好序的数组x 需要查找的数-1 无法查到数据 6 */ 7 public static int binarySearch(int[] arr, int x) { 8 int low = 0; 9 int high = arr.length-1; 10 while(low <= high) { 11 int middle = (low + high)/2; 12 if(x == arr[middle]) { 13 return middle; 14 }else if(x <arr[middle]) { 15 high = middle - 1; 16 }else { 17 low = middle + 1; 18 } 19 } 20 return -1; 21 }22 //递归实现二分查找23 public static int binarySearch(int[] dataset,int data,int beginIndex,int endIndex){ 24 int midIndex = (beginIndex+endIndex)/2; 25 if(data <dataset[beginIndex]||data>dataset[endIndex]||beginIndex>endIndex){ 26 return -1; 27 } 28 if(data <dataset[midIndex]){ 29 return binarySearch(dataset,data,beginIndex,midIndex-1); 30 }else if(data>dataset[midIndex]){ 31 return binarySearch(dataset,data,midIndex+1,endIndex); 32 }else { 33 return midIndex; 34 } 35 } 36 37 public static void main(String[] args) {38 int[] arr = { 6, 12, 33, 87, 90, 97, 108, 561 };39 System.out.println("循环查找:" + (binarySearch(arr, 87) + 1));40 System.out.println("递归查找"+binarySearch(arr,3,87,arr.length-1));41 }42 }
0 0
- 查找算法 二分查找
- 查找算法:二分查找
- 算法--查找--二分查找
- 查找算法---二分查找
- [算法]二分查找算法
- 算法----二分查找算法
- 查找算法:二分查找算法
- [转载]查找算法----二分查找
- 查找算法之二分查找
- 查找算法之二分查找
- 查找算法_二分查找
- 算法 二分查找(折半查找)
- 查找算法之二分查找
- 查找算法之二分查找
- 查找算法之二分查找
- 查找算法之二分查找
- 查找算法之二分查找
- 查找算法之二分查找
- MFC之下拉列表 ComboBox
- [后缀数组]ural1297 Palindrome
- sql in的参数化查询
- [代码实例][.NET]操作Excel文件
- Android Support v4、v7、v13的区别和应用场景
- 二分查找算法
- 猜数字游戏的提示 (Master-Mind Hints, UVa 340)
- 微信分享之因分享图片太大无法起调微信客户端
- 3个最好的PHP框架的Web开发
- 可新可新的新手刚刚上路,学C语言,见笑了,大神不用来了。(内有break与continue)
- Raft算法和开源实现
- Visual Studio 2015,OpenCV3.2 环境搭建记录
- Linux学习笔记-VMware Workstation 12 虚拟机搭建 CentOS 7 练习机
- 赶紧来许愿:canvas流星雨的背景