風行草偃

陪伴,是最长情的告白。

Java_二分法查找算法

Hung:

听说来有一种使用递归算法实现的,不过我没用过,用到了以后会再发帖子。




/**
    @author Hung
*/
public class Dichotomy {
    private int[] ints = new int[10];    
    private int num = 56;
    
     public Dichotomy(){
         this.initInts();
         this.sortInts();
         System.out.print("Array: ");
         for(int t : ints){
             System.out.print(t+"  ");
         }
         System.out.println("\nsearch: "+num);
         System.out.println("index: "+this.search(this.ints ,num));
     }
     
     /**
         二分法查找算法
     */
     private int search(int[] ints ,int num){
         int beginIndex = 0;
         int endIndex = ints.length-1;
         
         while(beginIndex<=endIndex){
            int mid = (beginIndex+endIndex)/2;
            if(num-ints[mid] > 0)
                beginIndex = mid+1;
            else if(num-ints[mid] < 0)
                endIndex = mid-1;
            else
                return mid;
        }
        return -1;
     }
     
     /**
         对数组进行排序
     */
     private void sortInts(){
         for(int i=ints.length-1 ;i>=0;i--){
             for(int j=0 ;j<ints.length-1 ;j++){
                if(ints[j]>ints[j+1]){
                    int t = ints[j];
                    ints[j] = ints[j+1];
                    ints[j+1] = t;
                }                 
             }
         }
     }
     
     /**
         初始化数组
     */
     private void initInts(){
         ints[0] = 12;    ints[1] = 34;
         ints[2] = 23;    ints[3] = 56;
         ints[4] = 12;    ints[5] = 43;
         ints[6] = 65;    ints[7] = 15;
         ints[8] = 67;    ints[9] = 98;
     }
     

    public static void main(String[] args){
         new Dichotomy();
    }
}

评论
热度 ( 2 )

© 風行草偃 | Powered by LOFTER