【问题标题】:Binary search doesn't stop? [closed]二进制搜索不会停止? [关闭]
【发布时间】:2020-06-09 09:58:47
【问题描述】:

我有以下二进制搜索方法和以下驱动程序代码。我在输出中搜索显示的两个值都存在于数组中。

搜索方法

    //Method for binary search. This method will also cut our array
    public static int binarySearch(int[] nums, int x) {
        //Bounds
        int l = 0, r = nums.length - 1;
        //While the size of the array is not 1
        while (l <= r) {
            //Middle element
            int m = l + (r - 1) / 2;
            //If our element is the middle
            if (nums[m] == x) return m;
            //If x is greater, cut to right half
            else if (x > nums[m]) l = m + 1;
            //Else, ignore right half
            else r = m - 1;
        }
        //If we didn't find the element
        return -1;
    }

驱动代码和输出

public class searcher {
    public static void main(String[] args) {
         /* Initialize a new scanner for user input, initialize random for the
        computer to pick a number */
        Scanner s = new Scanner(System.in);
        //Variable for user input
        int guess;
        //Do-while loop
        do {
            System.out.println("Enter a number to search for (0 to quit): ");
            //Get the user's guess
            guess = s.nextInt();
            //Search for the guess in the array of numbers
            int i = binarySearch(nums, guess);
            System.out.println(i);
            //If the number is not found
            if (i == -1) {
                System.out.println("Your number does not occur in this list.");
            }
            //If it is
            else {
                System.out.println("Your number occurs at position " + i);
            }
        } while (guess != 0);
    }
}
/*
Output
Enter a number to search for (0 to quit): 
1
1
Your number occurs at position 1
Enter a number to search for (0 to quit): 
90 
            <------- Program doesn't stop running from here...? */

如果找到输入的数字的索引,我希望得到一个输出,如果没有,该方法应该返回 -1,以便我可以打印未找到

【问题讨论】:

  • 您确定num 数组已排序?
  • @ b.m是的,它是指的,但我应该自己重新排序吗? span>
  • 提示: m = l + (r - 1) / 2 并不代表你认为的那样。为三个变量的值添加一些日志记录,您就会发现问题。
  • (我们可以根据“未命名为变量”@“。) span>
  • 尝试调试看看出了什么问题。 (例如记录间隔边界)

标签: java arrays algorithm binary-search


【解决方案1】:

你减去 1 两次。

r = nums.length - 1;

然后

int m = l + (r - 1) / 2;

应该是

int m = l + (r - l) / 2;

【讨论】:

  • 另外,“减一两次”并不是代码不起作用的实际解释。
【解决方案2】:
int m = l + (r - 1) / 2; // this is not correct, you are subtracting "1"

你需要减去“left”(为清楚起见编辑了变量名称):

int mid = left + (right - left) / 2;

或者,更好一点:

int mid = (left+ right) >>> 1;

【讨论】:

    猜你喜欢
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 2011-01-24
    • 2017-06-13
    相关资源
    最近更新 更多