算法06 五大查找之:二分查找


二分查找屬於順序表查找,二分查找也稱為折半查找。二分查找的時間復雜度為O(log2n)  

1、二分查找的定義

什么是二分查找呢?二分查找的基本思想是:在有序表中,取中間元素作為比較對象,若給定值與中間元素相等,則查找成功;若給定值小於中間元素,則在中間元素的左半區繼續查找;若給定值大於中間元素,則在中間元素的右半區繼續查找。不斷重復上述過程,直到找到為止。

從二分查找的定義我們可以看出,使用二分查找有兩個前提條件:

(1)待查找的列表必須有序。

(2)必須使用線性表的順序存儲結構來存儲數據。

2、二分查找的代碼實現

代碼:

BinarySearch.java

public class BinarySearch {
    public static void main(String[] args) {
        int[] list = {10, 20, 30, 40, 50, 60, 70, 80, 90};
        System.out.println("************二分查找************");
        display(list);
        System.out.println("");

        int result = binarySearch(list, 30);
        if (result != -1) {
            System.out.println("30在列表中的位置是:" + result);
        } else {
            System.out.println("對不起,列表中不存在該元素!");
        }
    }

    /**
     * 二分查找
     */
    public static int binarySearch(int[] list, int key) {
        int low = 0;
        int high = list.length - 1;

        while (low <= high) {
            int middle = (low + high) / 2;

            // 判斷中間元素是否與給定值相等
            if (list[middle] == key) {
                return middle;
            } else {
                if (list[middle] > key) {
                    // 在中間元素的左半區查找
                    high = middle - 1;
                } else {
                    // 在中間元素的右半區查找
                    low = middle + 1;
                }
            }
        }
        // 沒有找到(查找失敗)
        return -1;
    }

    /**
     * 遍歷打印
     */
    public static void display(int[] list) {
        System.out.println("********展示開始********");
        if (list != null && list.length > 0) {
            for (int num :
                    list) {
                System.out.print(num + " ");
            }
            System.out.println("");
        }
        System.out.println("********展示結束********");
    }
}

 

運行結果:

 

 

歡迎轉載,但請保留文章原始出處

本文地址:http://www.cnblogs.com/nnngu/p/8286401.html 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM