zoukankan      html  css  js  c++  java
  • 算法,折半查找--javascript版

    var arr = [1,2,4,6,9,10,12,15];
    function searchKey(arr, key) {
    	var mid = parseInt(arr.length/2);
    	var midValue = arr[mid]; 
    	if(key === midValue){
    		return midValue;
    	}else if(key > midValue){
    		return searchKey(arr.slice(mid+1), key);
    	}else if(key < midValue){
    		return searchKey(arr.slice(0, mid), key);
    	}else{
    		return false;
    	}
    }
    function print(arr, key) {
    	var res = searchKey(arr, key);
    	if(typeof res === "number") {
    		console.log("找到了");
    	}else{
    		console.log("呜呜,没找到!");
    	}
    }
    print(arr, 1);
    

      缺点是不能打印出准确位置;

      下面这种参考大神的写法;

    var arr = [1,2,4,6,9,10,12,15];
    function searchKey(arr, key) {
        var high = arr.length - 1;
        var low = 0,middle,midValue;
        while(low <= high) {
            middle = parseInt( (low + high) / 2 );
            midValue = arr[middle];
            if(midValue === key) {
                return middle;
            }else if(midValue > key){
                high = middle - 1;
            }else if(midValue < key){
                low = middle + 1;
            }else{
                return "错误的参数";
            }
        }
        return false;
        
    }
    function print(arr, key) {
        var res = searchKey(arr, key);
        if(typeof res === "number") {
            console.log("找到了,位置是" + res);
        }else{
            console.log("呜呜,没找到!");
        }
    }
    print(arr, 1);

     

  • 相关阅读:
    react结合antd4.0和umi3.0的404界面
    小程序自带组件自定义tabbar
    移动安全学习清单
    跨域资源共享 CORS 详解(转)
    docker常用命令总结
    XSS绕过小结
    mysql的order by注入
    本地文件包含漏洞利用姿势
    XSS绕过<>进行测试
    clamscan+clam-freshclam.service服务启停
  • 原文地址:https://www.cnblogs.com/tchlu/p/6026790.html
Copyright © 2011-2022 走看看