二分查找

二分查找

1. 二分查找的條件

必須是有序數組

2. 二分查找的思想

我們先將被查找的數和數組的中間鍵對應的value比較,因爲數組是有序的,所有若被查找的數小於數組的中間鍵對應的value則這個數則在數組的左部分,然後將中間鍵的左邊數組當作一個數組來進行二分查找。反之,則在數組的右部分,若相等,則查找成功。

3. 兩種實現方式

package com.zhmcode.binarysearch;

/**
 * Created by zhmcode on 2019/2/14 0014.
 */
public class MyBinarySearch {

    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 6, 8, 10, 11, 12};
        int value = 12;
        //int index = binarySearch1(value, arr);
        int index = binarySearch2(value,0,arr.length-1,arr);
        if (index == -1) {
            System.out.println("沒有查到數據");
        } else {
            System.out.println("查詢成功:當前索引爲" + index);
        }
    }

    /**
     * 循環方式
     */
    public static int binarySearch1(int value, int[] arr) {
        int min = 0;
        int max = arr.length - 1;
        while (min <= max) {
            int mid = (max + min) / 2;
            int value1 = arr[mid];
            if (value == value1) {
                return mid;
            } else if (value < value1) {
                max = mid - 1;
            } else {
                min = mid + 1;
            }
        }
        return -1;
    }

    /**
     * 遞歸方式
     */
    public static int binarySearch2(int value, int fromIndex, int toIndex, int[] arr) {
        int min = fromIndex;
        int max = toIndex;
        int mid = (min + max) / 2;
        int value1 = arr[mid];
        if (value < arr[min] || value > arr[max] || min > max) {
            return -1;
        }

        if (value == value1) {
            return mid;
        } else if (value < value1) {
            max = mid - 1;
            return binarySearch2(value, min, max, arr);
        } else {
            min = min + 1;
            return binarySearch2(value, min, max, arr);
        }
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章