You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java二分查找程序运行后终端无输出问题求助

二分查找程序无输出的问题修复

你的代码里存在关键逻辑错误,导致程序陷入死循环,因此终端没有输出。

错误点

在处理左半区间查找(即number[mid] > key的场景)时,你错误地修改了start变量:

else {  //left
    start = mid-1;
}

正确操作应该是缩小右边界,将end赋值为mid-1——因为此时目标值必然在左半区间,无需再考虑mid右侧的元素。

修正后的完整代码

import java.util.*;
public class BinarySearch {
    public static int binarySearch(int number[], int key) {
        int start = 0, end = number.length-1;
        while (start<=end) {
            int mid = (start+end)/2;

            //comparisons
            if (number[mid] == key) { //found
                return mid;
            }
            if (number[mid] < key) { //right
                start = mid+1;
            }
            else {  //left
                end = mid-1; // 此处修正为调整end变量
            }
        }
        return -1;
    }
    public static void main(String[] args) {
        int numbers[] = {2, 4, 6, 8, 10, 12, 14};
        int key = 10;
        System.out.println("index for key is " + binarySearch(numbers, key));
    }
}

运行结果

修正后运行程序,终端会输出:

index for key is 4

内容的提问来源于stack exchange,提问作者klaus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 18:52:39