和風細雨

          世上本無難事,心以為難,斯乃真難。茍不存一難之見于心,則運用之術自出。

          二分法查找示例

          package com.junglesong;

          /**
           * 二分查找示例
           * 
          @author: sitinspring(junglesong@gmail.com)
           * @date: 2008-3-8
           
          */

          public class BinSearch{
              
          public static void main(String[] args){
                  
          // 欲查找的數組
                  int[] arr={1,2,3,4,5,6,77,88,656,5000,40000};
                  
                  
          // 測試數組
                  int[] temp={4,5,6,77,88,656,1,2,400};        
                  
          for(int i:temp){
                      System.out.println(
          ""+i+"的下標為"+binSearch(arr,i));
                  }

              }

              
              
          /**
               * 二分查找
               * 
          @param sortedArray 已排序的欲查找的數組
               * 
          @param seachValue 查找的值
               * 
          @return 找到的元素下標,若找不到則返回-1
               
          */

              
          public static int binSearch(int[] sortedArray,int seachValue){
                  
          // 左邊界
                  int leftBound=0;
                  
          // 右邊界
                  int rightBound=sortedArray.length-1;
                  
          // 當前下標位置
                  int curr;
                  
                  
          while(true){
                      
          // 定位在左邊界和右邊界中間
                      curr=(leftBound+rightBound)/2;
                      
                      
          if(sortedArray[curr]==seachValue){
                          
          // 找到值
                          return curr;
                      }

                      
          else if(leftBound>rightBound){
                          
          // 左邊界大于右邊界,已經找不到值
                          return -1;
                      }

                      
          else{
                          
          if(sortedArray[curr]<seachValue){
                              
          // 當當前下標對應的值小于查找的值時,縮短左邊界
                              leftBound=curr+1;
                          }

                          
          else{
                              
          // 當當前下標對應的值大于查找的值時,縮短右邊界
                              rightBound=curr-1;
                          }

                      }

                  }

              }

          }

          代碼下載:
          http://www.aygfsteel.com/Files/junglesong/BinSearch20080308150836.rar

          posted on 2008-03-08 14:26 和風細雨 閱讀(412) 評論(0)  編輯  收藏 所屬分類: 算法

          主站蜘蛛池模板: 石棉县| 伊春市| 隆化县| 宁武县| 永昌县| 鹰潭市| 淄博市| 海口市| 内江市| 琼结县| 游戏| 双峰县| 义马市| 韶关市| 新宁县| 嵊泗县| 通化县| 互助| 綦江县| 清流县| 丹阳市| 彰化县| 华蓥市| 石台县| 依安县| 蒲城县| 万安县| 广河县| 滕州市| 阜新| 瑞安市| 横山县| 怀柔区| 松阳县| 沅陵县| 米林县| 苗栗县| 黎城县| 山阴县| 宝坻区| 文安县|