1. 程式人生 > >折半查找法

折半查找法

rgs 一段 nbsp ges log spa clas pre style

折半查找法的前提下就是排好序的數組。算了,直接上代碼吧,思路就是每次都拿中間的數比較,大於中間數的就取後面一段數繼續比較,否則就取前面的一段數繼續比較

static int[] a={1,3,5,6,9,10,29};//定義一組測試的數組
    static int b=9;//要從數組裏面查找的數
    public static void main(String[] args) {
        
        int result = search(0, a.length-1, b);
        System.out.println(result);
        
    }
    
public static int search(int start,int end,int value){ if(a[start]==value){ return start; } if(a[end]==value){ return end; } if(start>=end||start+1==end||a[start]>value||a[end]<value){ return -1; }
int middle=(start+end)/2; if(value>a[middle]){ start=middle; return search(start, end, value); }else if(value<a[middle]){ end=middle; return search(start, end, value); }else{ return middle;//找到了 } }

運行結果:

技術分享

折半查找法