首页 > 解决方案 > 如果找到特定数字,如何使此打印为真或假?

问题描述

我想进行二进制搜索以在我的数组列表中查找一个数字,如果找到它则打印 false 或 true?

我希望我的 targetValues 查看它们是否存在于 arr 列表中并打印 true 或 false

public static void main(String[] args) throws IOException {


        {

            int arr[] = {10,20,30,40};
        int targetValue[]= {10,25,40} 
        }

    }

这是我的二进制搜索代码

    public static boolean binarySearch(int[] arr, int n) {
        int first = 0;
        int last = arr.length-1;
        int mid;
        while (first <= last){
            mid = first + (last - first) / 2;
            if (n == arr[mid]) return true;
            else if (n < arr[mid]) last = mid - 1;
            else first = mid + 1;
        }
        return false;

    }

标签: java

解决方案


假设您的数组按升序排序,这应该有效:

    public static void main(String[] args) throws IOException {
            {
            int arr[] = {10, 20, 30, 40};
            int targetValue[] = {10, 25, 40};
            int index = 0;
            while (index < targetValue.length) {
                out.println("Search for " + targetValue[index] + " " + binarySearch(arr, targetValue[index]));
                index++;
            }

    }
    public static boolean binarySearch(int[] arr, int n) {
        int count = 0;
        int mid = (arr.length - 1) / 2;
        while (count < arr.length - 1) {
            if (n == arr[mid]) {
                return true;
            } else if (n < arr[mid]) {
                if (mid != 0) {
                    mid = mid - 1;
                } else {
                    return false;
                }
            } else {
                if (mid != arr.length - 1) {
                    mid = mid + 1;
                } else {
                    return false;
                }
            }
            count++;
        }
        return false;
    }

推荐阅读