zoukankan      html  css  js  c++  java
  • 折半查找

    给定一个整数X和整数A0,A1,…,AN-1,后者已经预先排序并在内存中,求下标i使得Ai = X , 如果X不在数据中则返回i = -1 。

    明显的解法是从左往右扫描,花费线性时间。但是这个算法没有用到该表已经排序这个事实。

    折半检索(binary search,二分法检索)策略:

    /**
     * Performs the standard binary search.
     *@return index where item is found, or -1 if not found.
     */
     public static <AnyType extends Comparable<? super AnyType>>
     int binarySearch( AnyType [] a , AnyType x )
     {
    	int low = 0 ; high = a.length - 1 ; 
    	while(low <= high )
    	{
    		int mid =(low + high)/2;
    		if(a[mid].compareTo(x)<0)
    			low = mid +1 ; 
    		else if (a[mid].compareTo>0)
    			high = mid -1 ; 
    		else return mid ;//Found
    	}
    	return NOT_FOUND ; //NOT_FOUND is defined as -1 ; 
     }
    

      复杂度为O(logN)。

  • 相关阅读:
    HDU 5794
    HDU 5794
    3070 Fibonacci 矩阵快速幂
    数论基础
    hdu 1061 Rightmost Digit 快速幂
    poj 2305 Basic remains java
    poj 1001 Exponentiation
    hdu 2054 A == B ? (java)
    java大数练习
    hdu3018 Ant Trip 欧拉回路
  • 原文地址:https://www.cnblogs.com/larrylawrence/p/3811331.html
Copyright © 2011-2022 走看看