算法——二分查找

/**
 * 
 */
package arithmetic;

/**
 * 二分查找, 要求:数据必须有序排列
 * 
 * 设数据量为N,复杂度为:log2(N)
 * 数据量翻倍时,复杂度加1,未翻倍时,倍数的临界会导致复杂度加1
 * 
 * @author zhangkexing
 *
 */
public class BinarySearch {
    
    int postion = -1;
    
    /**
     * 
     * @param array 原始数组
     * @param x 从数组中要查找的数字
     * @return 返回查找几次
     */
    public int binarySearch(int[] array,int x){
        int step = 0;
        int low = 0;
        int hight = array.length -1;
        
        while(low <= hight){
            ++ step;
            postion = (low + hight) /2;
            int data = array[postion];

            System.out.println("search:"+x+" postion:"+postion+" low:"+low+" hight:"+hight);
            if(data == x){
                return step;
            }else if(data > x){
                hight = postion - 1;
            }else{
                low = postion + 1;
            }
        }
        
        return -1;
    }
    public static void main(String[] args) {
        int len = 2049;
        int[] array = new int[len];
        for(int i=0;i<len;i++){
            array[i]=i;
        }
        
        int step = new BinarySearch().binarySearch(array, 70);
        if(step == -1){
            System.out.println("未查找到");
        }else{
            System.out.println("共执行"+ step+"次");
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 基本思想: 二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除...
    NEXTFIND阅读 518评论 0 1
  • 二分查找,也称折半查找目的:提高查找速度(当查找性能成为问题时,考虑使用二分查找) 使用前提:(较为严格)已经排好...
    NiceBlueChai阅读 364评论 0 0
  • 二分查找有两种实现:通过递归或循环 二分查找的前提是先要保证数组有序 递归 循环 github 完整代码 -- b...
    liaozb1996阅读 165评论 0 0
  • 二分查找基于索引,所以必须是有序的
    不右21阅读 143评论 0 0
  • 算法是什么?在这里参考一下维基的定义。 在数学和计算机科学/算学之中,算法/演算法/算则法(Algorithm)为...
    LuDSh阅读 641评论 0 1