java-二分查找

二分查找也叫折半查找,前提是數組是有序數組,下面來分析原理。

如果一個數組:

int arr[] = {1,2,3,4,5,6};

要查找1所在的索引值,那麼先確定最大索引值maxIndex和最小索引值minIndex,然後計算出中間的索引值和midIndex

int maxIndex = arr.length-1;
int minIndex = 0;
int midIndex = (minIndex + maxIndex)/2;

根據中間的索引值找到中間的元素和1,比較如下通過比較midValue和1的值,如果midValue比1大,那麼就在數組arr[minIndex]到arr[midIndex-1]裏面繼續和進行上面的比較結果,如果midValue比1小,那麼就在數組arr[minIndex+1]到arr[maxIndex]裏面繼續進行上面的比較,如果找到,則直接返回索引,如果沒有找到一直到minIndex > maxIndex結束,說明沒找到返回-1.

while (arr[midIndex] != value) {
     if (arr[midIndex] > value) {
         maxIndex = midIndex - 1;
     } else {
         minIndex = midIndex + 1;
     }
     if (minIndex > maxIndex) {
         return -1;
     }
     midIndex = (minIndex + maxIndex) / 2;
 }
 return midIndex;

如果所示:

這裏寫圖片描述

可以如果在1.2.3.4.5.6 裏面用二分查找找1需要 3次查找。

二分查找的時間複雜度爲:log2n
參考:http://blog.csdn.net/frances_han/article/details/6458067

完整代碼:

public class BinarySearch {
    public static void main(String[] args) throws Exception {
        int arr[] = {1, 2, 3, 4, 5, 6};
        int index = getIndex(arr, 1);
        System.out.println("index:" + index);
        int index = getIndex(arr, 7);
        System.out.println("index:" + index);
    }

    private static int getIndex(int[] arr, int value) {
        int minIndex = 0;
        int maxIndex = arr.length - 1;
        int midIndex = (minIndex + maxIndex) / 2;

        while (arr[midIndex] != value) {
            if (arr[midIndex] > value) {
                maxIndex = midIndex - 1;
            } else {
                minIndex = midIndex + 1;
            }
            if (minIndex > maxIndex) {
                return -1;
            }
            midIndex = (minIndex + maxIndex) / 2;
        }
        return midIndex;
    }
}
發佈了32 篇原創文章 · 獲贊 24 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章