1. 程式人生 > 其它 >HDUOJ-----(1329)Calling Extraterrestrial Intelligence Again

HDUOJ-----(1329)Calling Extraterrestrial Intelligence Again

二分查詢

【舉個例子】,你去圖書館找一本書,如果你知道這個書架上的書是按照編號有序排列,你會從頭開始一個一個找嗎?

你大概的思路是這樣的,先去中間看看,如果我找的書的編號比中間的大我就去左邊找,否則去右邊找。

這種思路就是我們的二分查詢法:

(1)二分查詢(折半查詢)

import java.util.Scanner;

public class BinarySearch {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] nums = {14,24,28,37,54,67,79,85,96,157,257,368};
        System.out.println("請輸入您要查詢的數字:");
        int target = scanner.nextInt();
        //需要左右兩個變數確定檢索範圍
        int left = 0;
        int right = nums.length -1;

        if (target < nums[0] || target > nums[nums.length-1]){
            System.out.println("您輸入的數字不存在!");
        }
        int b = -1;
        while (left <= right){//左右下標不重合就繼續
            int middle = (left+right)/2;
            if (nums[middle] == target){
                b = middle;
                break;
            }else if (nums[middle] > target){
                right = middle-1;
            }else {
                left = middle+1;
            }
        }

        System.out.println(b);

    }
}