package _04_常见算法;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        /**
         * 二分查找算法
         * 定义一个有序数组
         * {100,200,300,400,500,600,700,800}
         *
         * 通过键盘录入方式 查找数组当中元素是否存在
         */
        //1 键盘录入一个数字
        Scanner scanner = new Scanner(System.in);
        System.out.println("请录入要查找的数字");
        int number = scanner.nextInt();
        //2 定义一个数组
        int[] arr = {100,200,300,400,500,600,700,800};
        //3 定义start = 0  end=arr.length-1
        int start = 0;
        int end = arr.length - 1;
        //4 遍历数组拿到数组的每一个元素
        int index = -3;
        for (int i = 0; i < arr.length; i++) {
            // 中间值 (start+ end)/2   mid 中间索引
            int mid = (start + end) / 2;
            if(number == arr[mid]){
                index = mid;
                break;
            }else if(number > arr[mid]){
                start = mid + 1;
            }else if(number < arr[mid]){
                end = mid -1;
            }
        }
        // 判断index = -1
        if(index == -3){
            System.out.println("在数组当中没有找到元素");
        }else{
            System.out.println("查找元素位置在:"+ index +"这里");
        }
    }
}
