Java二分法尋找實現

來源:互聯網
上載者:User

標籤:開始   static   eval   rgs   結束   找不到   public   oid   turn   

public class Dichotomy {
    
    //定義尋找次數
    static int count = 0;
    
    public static void main(String[] args) {
        
        //定義數組
        int [] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        
        //二分法尋找
        int result = searchRecursive( array, 0, array.length - 1, 3);
        
        //列印結果
        System.out.println("二分法尋找結果為=" + result);
        System.out.println("尋找次數為=" + count);
    }
    
    /**
     * 執行遞迴二分尋找,返回第一次出現該值的位置
     *
     * @param array
     *            已排序的數組
     * @param start
     *            開始位置
     * @param end
     *            結束位置
     * @param findValue
     *            需要找的值
     * @return 值在數組中的位置,從0開始。找不到返回-1
     */
    private static int searchRecursive(int[] array, int start, int end, int findValue) {
        
        //數組如果為空白則返回-1
        if(array == null){
            
            return -1;
        }
        
        
        
        while(start <= end){
            
            count++;
            
            //擷取中間位置
            int middle = (start + end) / 2;
            
            //擷取中間值
            int middleValue = array[middle];
            
            if(middleValue == findValue){
                
                return middle;
            }else if(findValue < middleValue){
                
                end = middle - 1;
            }else{
                
                start = middle + 1;
            }
            
        }
        
        return -1;
    }
}

Java二分法尋找實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.