程序说明笔者都写在注释里面了,思想很简单,但是写代码的时候还是要注意一些细节,比如特殊情况的处理,防止死循环等

  1. package sixth; 
  2.  
  3. public class HalfSearch { 
  4.     /** 
  5.      * 这般查找 
  6.      * @param array 要查找的数组,数组必须是有序的 
  7.      * @param num  要查找的数 
  8.      * @return  返回的是数组所在数组的索引 
  9.      */ 
  10.     public int halfSearch(int[] array,int num){ 
  11.         //l表示低位游标,h表示高位游标,index指示之间位置的索引 
  12.         int index,l=0,h=array.length; 
  13.         index=array.length/2
  14.         //先排除首位与尾位两个位置,这两个位置比较特殊,用折半查找需要特殊指出 
  15.         if(num==array[0]) 
  16.         { 
  17.             return 0
  18.         } 
  19.         else if(num==array[array.length-1]) 
  20.         { 
  21.             return array.length-1
  22.         } 
  23.         //开始折半的循环,注意中断条件,防止死循环 
  24.         while((l+1)!=h) 
  25.         { 
  26.             if(num==array[index]) 
  27.             { 
  28.                 return index; 
  29.             } 
  30.             else if(num>array[index]) 
  31.             { 
  32.                 l=index; 
  33.                 index=(h+l)/2
  34.             }    
  35.             else 
  36.             { 
  37.                 h=index; 
  38.                 index=(h+l)/2
  39.             } 
  40.         } 
  41.         return -1
  42.     } 
  43.      
  44.     public static void main(String[] args) { 
  45.         int count=100
  46.         int[]array = new int[100]; 
  47.         Tool.initArray(count, array); 
  48.         HalfSearch hs=new HalfSearch(); 
  49.         System.out.println(hs.halfSearch(array, 100)); 
  50.     }