zoukankan      html  css  js  c++  java
  • 【前端算法1】二分查找

    一、 二分查找
    二分法查找,也称折半查找,是一种在有序数组中查找特定元素的搜索算法。查找过程可以分为以下步骤: (1)首先,从有序数组的中间的元素开始搜索,如果该元素正好是目标元素(即要查找的元素),则搜索过程结束,否则进行下一步。 (2)如果目标元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半区域查找,然后重复第一步的操作。 (3)如果某一步数组为空,则表示找不到目标元素。
    • /** 查找元素在有序数组中的index
       * 二分法查找,也称折半查找,是一种在有序数组中查找特定元素的搜索算法
       * ***/
      // 第一种 : 非递归实现二分查找
      function binarySearch(arr, targetValue) {
        let minIndex = 0; // 查找索引的最小值
        let maxIndex = arr.length - 1; // 查找索引的最大值
        while (minIndex <= maxIndex) {
          let midIndex = parseInt(''+(minIndex+maxIndex)/2); //取一个中间索引
      
          if (targetValue === arr[midIndex]) { // 先和中间值比较,如果相等,证明找到了,直接返回该索引
            return midIndex;
          } else if (targetValue > arr[midIndex]) { // 4,5,7,8,9
            minIndex = midIndex + 1; // 最小索引变成中间索引+1,在执行循环
          } else if (targetValue < arr[midIndex]) {
            maxIndex = midIndex - 1; // 最大索引变成中间索引-1,在执行循环
          }
        }
        return -1; // 证明没有找到
      }
      let arrNum = [1, 2, 3, 4, 5, 6, 8, 9];
      
      let result = binarySearch(arrNum, 8);
      console.log(result); // 6 (元素8的索引值)

    • /** 第二种 : 递归实现二分查找
       *  递归就是一种特殊的循环(函数循环调用自身),关键点在于要让自己停下来
       *  实现此递归函数可参照第一种方式,将循环中的关键参数抽出来传参
       *  此函数的关键参数为:arr, minIndex,maxIndex,targetValue
      * */
      function binarySearchSelf(arr,minIndex,maxIndex,targetValue) {
        if (minIndex > maxIndex) {
          return -1; // 当 minIndex 大于 maxIndex的时候,证明没有找到,结束循环
        }
        let midIndex = parseInt('' + (minIndex + maxIndex) / 2);
        if (targetValue === arr[midIndex]) {
          return midIndex;
        } else if (targetValue > arr[midIndex]) {
          return binarySearchSelf(arr, midIndex + 1, maxIndex, targetValue);
        } else if (targetValue < arr[midIndex]) {
          return binarySearchSelf(arr, minIndex, maxIndex-1, targetValue);
        }
      }
      // min=2 max=1 return -1
      let arrNum = [1,2,3,4,5,6,7,8,9,10,11,23,44,86];//min = 2, max=1.---- min > max ----> return -1
      const ret = binarySearchSelf(arrNum, 0, arrNum.length-1, 1);
      console.log(ret);
    • 扩展 ---> 结束循环的几种方式
    • /** 结束循环的几种方式:
       * 1. 条件不满足时
       * 2. break 跳出整个循环
       * 3. continue 跳出本次循环。执行下一次循环
       * 4. 当循环在函数中时,还可以用return 结束循环
       * ***/
      for (let i=0;i<5;i++){
        console.log(i);
        if (i === 1) {
          continue; // continue 跳出本次循环。执行下一次循环
        }
        console.log(i+1);
      
        if (i === 4) {
          break; // break 跳出整个循环
        }
        console.log(i+2);
      }
      // 0 1  2
      // 1
      // 2 3 4
      // 3 4 5
      // 4 5
  • 相关阅读:
    pandas--对axis=0,axis=1的理解
    启动secondarynamenode时报错
    5月27日经历问题(在有框架的情况下从无到有增加一套功能)
    5.21工作记录(修改页面跳转,去掉多余的js;增加图片清除功能)
    工作记录520
    5月14日经历问题
    idea快捷键
    Linux下常用redis指令
    初识lunix
    Redis
  • 原文地址:https://www.cnblogs.com/mailyuan/p/12205528.html
Copyright © 2011-2022 走看看