首页 > 解决方案 > 我对查看整数是否在数组中的二进制搜索一直在循环,有人知道为什么吗?(在 Java 中)

问题描述

我用于查看整数是否在数组中的二进制搜索一直在循环,有谁知道为什么会发生这种情况?顺便说一句,我是第一次使用二进制搜索。

我的 Java 代码在这里:

import java.util.Scanner;

public class testBeforeLearning {
        private int[] array;
        private int target;

        public testBeforeLearning(int[] array, int target){
            this.array = array;
        }

        private int low;
        private int high;
        private int mid;

        public Boolean actualSearch(){
            low = 0;
            high = array.length - 1;

            while (target != array[mid]){
                mid = (low + high)/2;

                if (target == array[mid]){
                    return true;
                }

                else if(target > array[mid]){
                    low = mid + 1;
                }
                else if (target < array[mid]){
                    high = mid - 1;
                }
            }
            return false;
        }

        public static void main(String[] args){

            Scanner input = new Scanner(System.in);

            int[] dataSet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

            System.out.println("Please input a number you want to search for in the array:\n");

            int target = input.nextInt();

            testBeforeLearning binarySearch = new testBeforeLearning(dataSet, target);
            System.out.println(binarySearch.actualSearch());

    }
}


出于某种原因,我的下限和上限似乎没有增加或减少,我不知道为什么,有人知道为什么吗?

谢谢!

标签: javadata-structureswhile-loopbinary-search

解决方案


您已将 while 条件设置为 target != array[mid]。但是由于目标未初始化(默认为 0)并且数组中不存在 0,因此它将永远存在。您必须在 testBeforeLearning 中设置目标的值。附带说明一下,您可能还应该使 while 条件低 <= 高。


推荐阅读