# Binary Search Help

• March 29th, 2011, 02:02 AM
OwsumEmam
Binary Search Help
Binary Search Help

Code :

```class BinarySearch { public static void main(String[] args) { int data[] = {9,11,23,43,54,66,76,78,99}; int beg = data[0]; int end = data[data.length-1]; int mid = (int)((end-beg)/2); int item = 78; int loc = 0; do { if(item<data[mid]) { end = mid-1; } else beg = mid+1; mid = (int)((end-beg)/2); } while(beg<=end && data[mid]!=item);   if(data[mid]==item) System.out.println("Successful"); else System.out.println("Unsuccessful"); } }```
• March 29th, 2011, 06:20 AM
Mr.777
Re: Binary Search Help
1. Post your code in code tags.
2. Try learning indentation from here.
3. You are assigning the values to the variables beg, end, data values of array, not actually the index of array.
4. You should also have to check if your code finds out the specific value or not, if not then???
• March 30th, 2011, 11:49 PM
OwsumEmam
Re: Binary Search Help
Sorry brother, now it's right...!!! but can you help me out of this?
• March 30th, 2011, 11:50 PM
OwsumEmam
Re: Binary Search Help
how can i call the index without loops?
• March 31st, 2011, 12:46 AM
Mr.777
Re: Binary Search Help
Code java:

```mid=(end+beg)/2 not mid=(end-beg)/2;```
• March 31st, 2011, 09:28 AM
OwsumEmam
Re: Binary Search Help
But the prob is the same IndexOutOfBoundsException : 54 (first it was on 45)
• March 31st, 2011, 09:15 PM
Junky
Re: Binary Search Help
You set beg and end to values in the array not the first and last index of the array.
• March 31st, 2011, 11:01 PM
Mr.777
Re: Binary Search Help
Why are you doing this?
Code java:

```int beg=data[0];// wrong actually you are assigning value here but you should assign index. //So do, int beg=0; int end=data.length()-1;```