zoukankan      html  css  js  c++  java
  • java 实现二分查找法

    /**
     * 二分查找又称折半查找,它是一种效率较高的查找方法。 
      【二分查找要求】:1.必须采用顺序存储结构 2.必须按关键字大小有序排列。
     * @author Administrator
     *
     */
    public class BinarySearch { 
        public static void main(String[] args) {
            int[] src = new int[] {1, 3, 5, 7, 8, 9}; 
            System.out.println(binarySearch(src, 3));
            System.out.println(binarySearch(src,3,0,src.length-1));
        }
    
        /**
         * * 二分查找算法 * *
         * 
         * @param srcArray
         *            有序数组 *
         * @param des
         *            查找元素 *
         * @return des的数组下标,没找到返回-1
         */ 
       public static int binarySearch(int[] srcArray, int des){ 
        
            int low = 0; 
            int high = srcArray.length-1; 
            while(low <= high) { 
                int middle = (low + high)/2; 
                if(des == srcArray[middle]) { 
                    return middle; 
                }else if(des <srcArray[middle]) { 
                    high = middle - 1; 
                }else { 
                    low = middle + 1; 
                }
            }
            return -1;
       }
          
          /**  
         *二分查找特定整数在整型数组中的位置(递归)  
         *@paramdataset  - 待查数组
         *@paramdata     - 查找元素
         *@parambeginIndex  - 范围开始下标
         *@paramendIndex   - 范围结束下标
         *@returnindex  - 返回下标值
         */
        public static int binarySearch(int[] dataset,int data,int beginIndex,int endIndex){  
           int midIndex = (beginIndex+endIndex)/2;  
           if(data <dataset[beginIndex]||data>dataset[endIndex]||beginIndex>endIndex){
               return -1;  
           }
           if(data <dataset[midIndex]){  
               return binarySearch(dataset,data,beginIndex,midIndex-1);  
           }else if(data>dataset[midIndex]){  
               return binarySearch(dataset,data,midIndex+1,endIndex);  
           }else {  
               return midIndex;  
           }  
       } 
    
    }
  • 相关阅读:
    BNU 51002 BQG's Complexity Analysis
    BNU OJ 51003 BQG's Confusing Sequence
    BNU OJ 51000 BQG's Random String
    BNU OJ 50999 BQG's Approaching Deadline
    BNU OJ 50998 BQG's Messy Code
    BNU OJ 50997 BQG's Programming Contest
    CodeForces 609D Gadgets for dollars and pounds
    CodeForces 609C Load Balancing
    CodeForces 609B The Best Gift
    CodeForces 609A USB Flash Drives
  • 原文地址:https://www.cnblogs.com/xingzc/p/5774227.html
Copyright © 2011-2022 走看看