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

基于数据集的二分查找:请求协助返回数据集3中的特定数据

实现基于数据集3的二分查找查询

看起来你已经写好了二分查找的核心逻辑,但main方法还没写完对吧?我来帮你补全代码,同时实现针对数据集3的特定数据查询功能:

完整代码实现

import java.util.Scanner;

public class BinarySearchDemo {
    // 你的二分查找核心方法
    public static int binarySearch(int[] list, int key) {
        int low = 0;
        int high = list.length - 1;
        while (high >= low) {
            int mid = (low + high) / 2;
            if (key < list[mid])
                high = mid - 1;
            else if (key == list[mid])
                return mid;
            else
                low = mid + 1;
        }
        return -low - 1; // 未找到时返回插入点的负数形式
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        // 定义数据集,你可以把dataset3替换成实际的目标数据集
        int[] dataset3 = {15, 22, 37, 41, 53, 66, 72, 88}; 
        
        System.out.print("请输入要查找的关键字:");
        int key = in.nextInt();
        
        int result = binarySearch(dataset3, key);
        if (result >= 0) {
            System.out.println("关键字 " + key + " 在数据集3中的索引位置是:" + result);
        } else {
            int insertPosition = -result - 1;
            System.out.println("关键字 " + key + " 未在数据集3中找到,若要保持数组有序,建议插入位置:" + insertPosition);
        }
        
        in.close();
    }
}

关键说明

  • 我直接把代码聚焦到数据集3的场景,你可以替换dataset3里的数组内容为你的实际数据
  • 二分查找方法的返回值逻辑:
    • 正数:表示找到关键字,返回其在数组中的索引位置
    • 负数:表示未找到,通过-result -1可以算出该关键字应该插入的位置(保证数组仍有序)
  • 运行后只需输入要查询的关键字,就能得到对应的结果反馈

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:27:38