zoukankan      html  css  js  c++  java
  • xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

    js binary search algorithm

    js 二分查找算法

    二分查找, 前置条件

    1. 存储在数组中
    2. 有序排列

    理想条件: 数组是递增排列,数组中的元素互不相同;

    重排 & 去重

    顺序: 递增排列/递减排列;
    重复: 数组中存在相同的元素;

    
    "use strict";
    
    /**
     *
     * @author xgqfrms
     * @license MIT
     * @copyright xgqfrms
     * @created 2020-05-20
     * @modified
     *
     * @description 二分查找 binary-search
     * @augments
     * @example
     * @link
     *
     */
    
    const log = console.log;
    
    function binarySearch(data, key, preIndex = 0, debug = false){
      let len = data.length;
      // 向下取整
      let half = Math.floor(len/2);
       // 差值
      let diffValue = key - data[half];
      if(debug) {
        // preIndex 保留上次的索引值 indexOf
        log(`
    preIndex`, preIndex)
        log(`len`, len)
        log(`half`, half)
        log(`key`, key)
        log(`data[half]`, data[half])
        // number - undefined == NaN
        log(`diffValue`, diffValue)
      }
      if (diffValue > 0) {
        preIndex = preIndex + half + 1;
        let right = data.slice(half + 1);
        return binarySearch(right, key, preIndex);
      } else if (diffValue < 0) {
        let left = data.slice(0, half);
        return binarySearch(left, key, preIndex);
      }else if (diffValue === 0) {
        return preIndex + half;
      } else {
        return -1;
      }
    }
    
    
    
    let v4 = binarySearch([1,3,5,7,9], 9);
    log(`v4`, v4)
    // 4
    
    let v11 = binarySearch([1,3,5,7,9], 11);
    log(`v11`, v11)
    // -1
    
    // binarySearch(5, [1,2,3,4,5,6,7,8]);
    // // 4
    // binarySearch(5, [1,3,5,7,9]);
    // // 2
    // binarySearch(1, [1,3,5,7,9]);
    // // 0
    // binarySearch(7, [1,3,5,7,9]);
    // // 3
    // binarySearch(9, [1,3,5,7,9]);
    // // -1
    
    
    

    BST

    
    function binarySearch(target,arr,start,end) {
        if( start > end){
            return -1
        }
        var start   = start || 0;
        var end     = end || arr.length-1;
        var mid = parseInt(start + (end-start)/2);
        if(target==arr[mid]){
            return mid;
        }else if(target>arr[mid]){
            return binarySearch(target, arr, mid+1, end);
        }else{
            return binarySearch(target, arr, start, mid-1);
        }
        return -1;
    }
    
    binarySearch(9,[1,2,3,4,5,7,8])
    // -1
    
    

    https://www.jianshu.com/p/eef65b21ace0

    Big O


    Flag Counter

    ©xgqfrms 2012-2020

    www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


  • 相关阅读:
    dp 简单例题poj 1260 Pearls
    多校赛 Barareh on Fire
    中国剩余定理的简单应用 poj 1006 Biorhythms
    CF 5A. Chat Server's Outgoing Traffic
    springmvc使用aop心得
    Firefox添加插件支持修改Headers
    提高网站打开速度的18点要素
    用maven打包项目成war文件
    springmvc使用@ResponseBody返回json乱码解决方法
    用JS实现删除买家信息(阿里巴巴模拟笔试)
  • 原文地址:https://www.cnblogs.com/xgqfrms/p/12927211.html
Copyright © 2011-2022 走看看