二分查找法
来源:互联网 发布:淘宝宝贝描述模素材 编辑:程序博客网 时间:2024/06/05 20:10
题目:二分查找法
递归和非递归两种方式:
转载出处:http://blog.csdn.net/jiandanfeng2/article/details/6525193
二分查找又称折半查找,它是一种效率较高的查找方法。
【二分查找要求】:1.必须采用顺序存储结构 2.必须按关键字大小有序排列。
【二分查找要求】:1.必须采用顺序存储结构 2.必须按关键字大小有序排列。
java代码如下:
public class BinarySearch { public static void main(String[] args) { int[] src = new int[] {1, 3, 5, 7, 8, 9}; System.out.println(binarySearch(src, 3)); System.out.println(binarySearch(src,3,0,src.length-1)); } /** * * 二分查找算法 * * * * @param srcArray * 有序数组 * * @param des * 查找元素 * * @return des的数组下标,没找到返回-1 */ public static int binarySearch(int[] srcArray, int des){ int low = 0; int high = srcArray.length-1; while(low <= high) { int middle = (low + high)/2; if(des == srcArray[middle]) { return middle; }else if(des <srcArray[middle]) { high = middle - 1; }else { low = middle + 1; } } return -1; } /** *二分查找特定整数在整型数组中的位置(递归) *@paramdataset *@paramdata *@parambeginIndex *@paramendIndex *@returnindex */ public static int binarySearch(int[] dataset,int data,int beginIndex,int endIndex){ int midIndex = (beginIndex+endIndex)/2; if(data <dataset[beginIndex]||data>dataset[endIndex]||beginIndex>endIndex){ return -1; } if(data <dataset[midIndex]){ return binarySearch(dataset,data,beginIndex,midIndex-1); }else if(data>dataset[midIndex]){ return binarySearch(dataset,data,midIndex+1,endIndex); }else { return midIndex; } } }
输入结果为角标:
1
阅读全文
0 0
- 查找----二分查找法
- 二分查找法,查找string
- 二分查找法
- 二分查找法
- 二分查找法
- 二分查找法
- java 二分查找法
- 二分查找法
- 二分查找法
- 二分查找法
- 二分查找法
- java:二分查找法
- C++ 二分查找法
- 二分查找法
- 【二分查找法】
- php二分查找法
- 二分查找法
- 二分查找法
- 工科硕士论文评阅面面观
- centos7firewall防火墙操作
- Mysql only_full_group_by以及其他关于sql_mode原因报错详细解决方案
- C标准库常用函数实现
- Unity3D 旋转矩阵 顶点动画
- 二分查找法
- shell执行linux命令
- 局域网内固定自己的ip
- Android中MVP架构模式详解
- boost::shared_ptr 的作为参数传递,以及构造细节!
- 在java程序中制作动图
- 任何通过github搭建个人网页
- ActiveMQ、RabbitMQ和Kafka的简单对比
- AAC(高级音频编码)帧格式及编码介绍