和風(fēng)細(xì)雨

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

          二分法查找示例

          package com.junglesong;

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

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

              }

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

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

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

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

                          
          else{
                              
          // 當(dāng)當(dāng)前下標(biāo)對應(yīng)的值大于查找的值時,縮短右邊界
                              rightBound=curr-1;
                          }

                      }

                  }

              }

          }

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

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

          主站蜘蛛池模板: 馆陶县| 张掖市| 黑河市| 泊头市| 天柱县| 通海县| 米泉市| 成都市| 大埔县| 黑山县| 吴桥县| 楚雄市| 洪湖市| 九龙城区| 大港区| 治多县| 资兴市| 方山县| 北流市| 土默特右旗| 湖南省| 太保市| 会昌县| 崇州市| 阜康市| 昔阳县| 当涂县| 和平县| 宜城市| 攀枝花市| 岚皋县| 同心县| 江华| 阿瓦提县| 子洲县| 永川市| 新乡市| 昔阳县| 于田县| 大悟县| 张家港市|