java - 如果找到特定数字,如何使该打印正确或错误?

标签 java

我想做一个二分搜索来找到我的数字 arraylist 并在找到时打印 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;

    }

最佳答案

假设您的数组按升序排序,这应该可行:

    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;
    }

关于java - 如果找到特定数字,如何使该打印正确或错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58415267/

相关文章:

java - 显示可滚动的 JTable

java UnsatisfiedLinkError awt.image

java - Spring MVC + hibernate : a form with checkboxes for @manytomany relationship

java - 当相对布局包含自定义 View 时滚动它

java - 带按钮的滑动菜单

java - Spring Validation 中的单元测试自定义 validator

java - 将数据保存在ArrayList的ArrayList中

java - 关闭客户端和服务器后孤立的 TCP 连接

java - 为什么将微服务分布式事务模式命名为 SAGA?

javascript - 套接字服务器无法与 JavaScript 套接字客户端连接