【问题标题】:Simple Binary Search Program....Please tell me what is wrong in this specific code简单的二进制搜索程序....请告诉我这个特定代码有什么问题
【发布时间】:2014-12-30 10:49:16
【问题描述】:

我是初学者。 这是一个二进制搜索代码。它显示主方法的数组越界错误。 请查看该程序并告诉我我的错误。感谢您的服务。 我必须写所有这些废话,因为我不能发布它,因为它要求更多细节。

public class BinaryS
{
    int n;

    public BinaryS(int z)
    {
    n=z;

    }

    static int pos;
    static boolean flag=false;
    public void disp()
    {
        int arr[]={0,1,2,3,4};
        int len=arr.length;
        int first=0;
        int last=len;
        int mid=(int)(first+last/2);
        //boolean flag=false;
        while(mid>=0 && mid<=len)
        {
        if(n<arr[mid])
        {
            last=mid;
        }
     if(n>arr[mid])
     {
         first=mid;

        }
        if(n==arr[mid])
        {
            flag=true;
            pos=mid+1;
        }
    }
    if(flag==true){
    System.out.println("the no."+n+"is found at"+pos);
    }
    else{
    System.out.println("the no."+n+"is not found ");
    }
    }
     public static void main(String args[])
     {
         BinaryS obj=new BinaryS(2);
         obj.disp();

     }
}

【问题讨论】:

  • 首先要修复:缩进。现在到处都是。正确缩进它,我们所有人都会更容易阅读,包括你自己。接下来,更清楚地描述问题,以及您为尝试诊断它所做的工作。 (你说它没有编译但它一直在运行,这对我来说听起来很矛盾......你需要非常准确地了解你所看到的。)
  • 编译错误应该很容易修复。它会告诉你犯错的类名和行号。我的建议是清理编译错误并在遇到运行时问题时返回。

标签: java search compiler-errors binary


【解决方案1】:

目前您的代码确实可以编译,并且永远运行 - 因为这个循环:

while(mid>=0 && mid<=len)
{
    // Code which doesn't modify mid or len
}

假设它完全进入了那个循环(确实如此),条件永远不会变为假 - 所以除非你从循环中返回或中断(你没有)或抛出异常(它是't) 你会继续循环下去。

这是你应该去的地方:

  • 使用调试器观察正在发生的事情
  • 想想条件应该实际上是什么,以及你希望它如何变为假
  • 调整您的代码以更改条件,或更改循环体以修改midlen

【讨论】:

  • 编辑它添加--while(mid>=0 && mid
  • 问题是你不懂二分查找算法:en.wikipedia.org/wiki/Binary_search_algorithm
  • @anurag1018:现在是学习使用调试器、了解代码在做什么的好时机。
  • 我很乐意这样做。如果你能指导我如何在 Eclipse 中使用它,我将不胜感激。
  • @anurag1018:不,这并不是真正的 SO 工作方式。网络上有 大量 调试教程 - 我建议您搜索一个。
猜你喜欢
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
  • 2022-06-15
相关资源
最近更新 更多