和風(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)對(duì)應(yīng)的值小于查找的值時(shí),縮短左邊界
                              leftBound=curr+1;
                          }

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

                      }

                  }

              }

          }

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

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

          主站蜘蛛池模板: 察隅县| 什邡市| 漳州市| 虞城县| 宁南县| 禄丰县| 收藏| 治多县| 徐汇区| 兴义市| 偏关县| 平阴县| 鄂托克前旗| 即墨市| 四平市| 永靖县| 体育| 扶沟县| 花莲市| 巴南区| 屏东市| 栾川县| 同心县| 洪泽县| 涟源市| 会泽县| 临江市| 大理市| 中西区| 晋中市| 杭锦后旗| 句容市| 襄汾县| 石家庄市| 印江| 定边县| 西充县| 长宁区| 区。| 鄢陵县| 正镶白旗|