0
public class Sorting 
{


    public static void main(String[] args)
    {
        int j=10;
        int[] arr=new int[10];
        for(int i=0;i<arr.length;i++)
        {
            arr[i]=j;
            j+=10;
        }


        int num=Integer.parseInt(args[0]);
        bsearch(arr,0,10,num);


    }
    static void bsearch(int[] arr2,int first,int last,int key)
    {

        while(first<=last)
        {
            int mid=(first+last)/2;
            if(key==arr2[mid])
            {
            System.out.println("Found the key");
            }
            else if(key<arr2[mid])
            {
                last=mid-1;
            }
            else if(key>arr2[mid])
            {
                first=mid+1;
            }
            else
            {
                System.out.println("Did not find the key");
            }
        }
    }
}

Edited by mike_2000_17: Fixed formatting

3
Contributors
6
Replies
7
Views
6 Years
Discussion Span
Last Post by NormR1
0

Please copy and paste any error messages here.
If no errors, explain your problem.

Hi,
I am getting an exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Sorting.main(Sorting.java:17)
Hope this helps u to find the problem

0

Look at your program at line 17. What statement is at that line that uses an array?

What is the size of the array that you are trying to look at the first element: [0]?
Does it have any elements at all?

Edited by NormR1: n/a

0

Your array is size 10. You are passing in the 'last' number as 10 while your sort seems to look for size 11 (0~10). Remember that array index is 0-index, not 1-index. You need to pass in a number less than size by 1 or do your loop up to but not include the max size.

try to change this line...

while(first<=last) {

to...

while(first<last) {

and then tell me if it is still broken.

PS: Please put your code in the CODE tag... It's difficult to read with plain text format...

Edited by Taywin: n/a

0

Look at your program at line 17. What statement is at that line that uses an array?

What is the size of the array that you are trying to look at the first element: [0]?
Does it have any elements at all?

1.The line at 17 is to take arguments from command line.But i commented it later.

2.The size of array is 10.It is taking the elements but the search ain't happening. Something wrong.I changed calling method to bsearch(arr,0,10,11);.But the o/p window shows nutin.

0

Something wrong

Try debugging the code by adding some println() statements to show the variables values as they are used and changed.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.