zoukankan      html  css  js  c++  java
  • 二分搜索法

        二分搜索法,它充分利用了元素间的次序关系,采用分治策略,可在最坏的情况下用O(log n)完成搜索任务。它的基本思想是,将n个元素分成个数大致相同的两半,取a[n/2]与欲查找的x作比较,如果x=a[n/2]则找到x,算法运算终止。

       总结一下,二分搜索需要注意的点有以下几条:

    1. 数组一定记得要先排序!!!(不排序会出现各种莫名其妙的返回值)
    2. 取中位值的时候,需要注意整数加法是否会溢出的问题。
    3. 当查找不在数组内的元素时,需要返回-1代表没有找到。
    4. 如果出现待查找元素有重复的元素,需要确定返回的是哪一个元素的下标。
    5. /**
           * description : 二分查找。
           * @param array 需要查找的有序数组
           * @param from 起始下标
           * @param to 终止下标
           * @param key 需要查找的关键字
           * @return
           */
          public static <E extends Comparable<E>> int binarySearch(E[] array, int from, int to, E key) throws Exception {
              if (from < 0 || to < 0) {
                  throw new IllegalArgumentException("params from & length must larger than 0 .");
              }
              if (from <= to) {
                  int middle = (from >>> 1) + (to >>> 1); // 右移即除2
                  E temp = array[middle];
                  if (temp.compareTo(key) > 0) {
                      to = middle - 1;
                  } else if (temp.compareTo(key) < 0) {
                      from = middle + 1;
                  } else {
                      return middle;
                  }
              }
              return binarySearch(array, from, to, key);
          }

      这是二分搜索法的代码例题。

  • 相关阅读:
    CentOS7 安装 JIRA 7.2.x 教程:下载、安装、汉化、破解
    安装 GraphicsMagick
    CentOS 7 yum 安装 Nginx
    CentOS 安装 OpenResty
    软件工程技术面试个人指南
    五线谱
    中央C-高低音谱号里的中央C和其它音节
    使用管道copy同一文件至多个目录下
    refusing to merge unrelated histories
    Viewing A Specific Commit_12
  • 原文地址:https://www.cnblogs.com/F9801/p/8963226.html
Copyright © 2011-2022 走看看