zoukankan      html  css  js  c++  java
  • 改进的二分查找

     1 import java.util.Comparator;
     2 
     3 public class MyUtil {
     4 
     5    public static <T extends Comparable<T>> int binarySearch(T[] x, T key) {
     6       return binarySearch(x, 0, x.length- 1, key);
     7    }
     8 
     9    // 使用循环实现的二分查找
    10    public static <T> int binarySearch(T[] x, T key, Comparator<T> comp) {
    11       int low = 0;
    12       int high = x.length - 1;
    13       while (low <= high) {
    14           int mid = (low + high) >>> 1;
    15           int cmp = comp.compare(x[mid], key);
    16           if (cmp < 0) {
    17             low= mid + 1;
    18           }
    19           else if (cmp > 0) {
    20             high= mid - 1;
    21           }
    22           else {
    23             return mid;
    24           }
    25       }
    26       return -1;
    27    }
    28 
    29    // 使用递归实现的二分查找
    30    private static<T extends Comparable<T>> int binarySearch(T[] x, int low, int high, T key) {
    31       if(low <= high) {
    32         int mid = low + ((high -low) >> 1);
    33         if(key.compareTo(x[mid])== 0) {
    34            return mid;
    35         }
    36         else if(key.compareTo(x[mid])< 0) {
    37            return binarySearch(x,low, mid - 1, key);
    38         }
    39         else {
    40            return binarySearch(x,mid + 1, high, key);
    41         }
    42       }
    43       return -1;
    44    }
    45 }

    上面的代码中给出了折半查找的两个版本,一个用递归实现,一个用循环实现。需要注意的是计算中间位置时不应该使用(high+ low) / 2的方式,因为加法运算可能导致整数越界,这里应该使用以下三种方式之一:low + (high - low) / 2或low + (high – low) >> 1或(low + high) >>> 1(>>>是逻辑右移,是不带符号位的右移)

    转自:https://blog.csdn.net/jackfrued/article/details/44921941

    纸上得来终觉浅,绝知此事要躬行。
  • 相关阅读:
    某公司基于FineBI数据决策平台的试运行分析报告
    perl AnyEvent
    perl 微信 获取消息
    公司里的人际界线——北漂18年(41)
    perl URLencode URLdecode的方法
    Exception:org.eclipse.m2e.wtp.MarkedException: Unable to configure OHBC
    获取DIV内部内容报错
    JsViews Error:Unknown template:“#projectData”
    jQuery获取checkbox选中的值
    nginx mongodb相关配置
  • 原文地址:https://www.cnblogs.com/chenglangpofeng/p/10676812.html
Copyright © 2011-2022 走看看