Simple Binary Search Program....Please tell me what is wrong in this specific code

Im a beginner. Here is a binary search code.Its showing array out of bounds error for main method. please look into the program and kindly tell me my mistake.ill be grateful for ur service. i have to write all this crap cause i cant post it as its asking for more details.

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();

     }
}
Jon Skeet
people
quotationmark

Currently your code does compile, and runs forever - because of this loop:

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

Assuming it gets into that loop at all (which it does), the condition is never going to become false - so unless you return or break from within the loop (you don't) or an exception is thrown (it isn't) you're just going to keep going round the loop.

This is where you should:

  • Use a debugger to observe what's happening
  • Think about what the condition should actually be and how you want it to become false
  • Adjust your code to either change the condition, or change the loop body so that it modifies mid or len

people

See more on this question at Stackoverflow