Java数组之二分查找

import java.util.Scanner;

public class BinarySearch {
    public static void main(String[] args) {
        System.out.println("please input numbers count:");
        Scanner scan = new Scanner(System.in);
        int count = scan.nextInt();
        int[] numbers = new int[count];
        System.out.println("please input ordered numbers:");
        for (int i = 0; i < numbers.length; i++) {

            numbers[i] = scan.nextInt();
        }

        System.out.println("please input you want to find number:");
        int target = scan.nextInt();
        int start = 0;
        int end = numbers.length - 1;
        boolean find = false;
        while (start < end){
            int mid = (end + start) / 2;
            if(target == numbers[mid]){
                System.out.println("we find target number, it is " + (mid + 1) + " number.");
                find = true;
                break;
            }
            else if(target > numbers[mid]){
                start = mid + 1;
            }
            else if(target < numbers[mid]){
                end = mid - 1;
            }
        }

        if(!find){
            System.out.println("we can not find target number.");
        }
    }
}

//    please input numbers count:
//    14
//    please input ordered numbers:
//    2
//    4
//    5
//    8
//    12
//    15
//    19
//    26
//    37
//    49
//    51
//    66
//    89
//    100
//    please input you want to find number:
//    2
//    we find target number, it is 1 number.



//    please input numbers count:
//    14
//    please input ordered numbers:
//    2
//    4
//    5
//    8
//    12
//    15
//    19
//    26
//    37
//    49
//    51
//    66
//    89
//    100
//    please input you want to find number:
//    200
//    we can not find target number.
posted @ 2023-05-17 06:10  无风听海  阅读(8)  评论(0编辑  收藏  举报