# Problem with a binary search

• January 6th, 2014, 06:54 PM
AWol
Problem with a binary search
I am attempting to write basic code for a binary search. Here is the code I have:

Code Java:

```  public class BinarySearch { public static final int NOT_FOUND = -1; public static int binarysearch(int [] a, int x) { int low = 0; int high = a.length - 1; int mid; while(low<=high) { mid = (low + high) / 2; if(a[mid].compareTo(x) < 0) low = mid + 1; else if(a[mid].compareTo(x) > 0) high = mid - 1; else return mid; } return NOT_FOUND; } public static void main(String [] args) { int SIZE = 6; int [] a = new Integer[SIZE] = {-3, 5, 10, 10.5, 24, 45.3}; System.out.println("45.3 found at " + binarysearch(a,45.3)); } }```

However, when I attempt to compile, I am given a message that says this line of code:
Code Java:

`int [] a = new Integer[SIZE] = {-3, 5, 10, 10.5, 24, 45.3};`
has an "illegal start of expression". I don't know what this means much less how to fix it.

Help would be much appreciated. Thank You!
• January 7th, 2014, 02:21 AM
andbin
Re: Problem with a binary search
Quote:

Originally Posted by AWol
However, when I attempt to compile, I am given a message that says this line of code:
Code Java:

`int [] a = new Integer[SIZE] = {-3, 5, 10, 10.5, 24, 45.3};`

If the variable is int[], you must instantiate an int[] .... not an Integer[]. And the syntax is also wrong for 2 reasons:
a) The '=' before '{' is wrong.
b) If you specify the size in [ ] you can't put { } with values. Either a size, or initialized values ... never both.

Thus:
int[] a = new int[] {-3, 5, 10, 10.5, 24, 45.3};
or more simply
int[] a = {-3, 5, 10, 10.5, 24, 45.3};
• January 7th, 2014, 01:33 PM
AWol
Re: Problem with a binary search
Thank You!

Another error is popping up now, saying that this line:

Code Java:

`if(a[mid].compareTo(x) < 0)`

is not good. The error says "int cannot be dereferenced".

I am taking a beginning class which is very very poorly put together, and all of your help is really really appreciated. Thank You so much!!
• January 7th, 2014, 01:36 PM
andbin
Re: Problem with a binary search
Quote:

Originally Posted by AWol
Code Java:

`if(a[mid].compareTo(x) < 0)`

is not good. The error says "int cannot be dereferenced".

An int is not an object ..... ;)
Compare ints simply using relational operators (< , > , etc ...)
• January 7th, 2014, 01:52 PM
AWol
Re: Problem with a binary search
I'm sorry I'm just not following... Like I said this class will explain what you're supposed to do, give a short example (in which I'm finding out the code is not even valid) and say "ok now do it"... So I'm sort of lost.

What would I have to change it to?
• January 7th, 2014, 05:18 PM
GregBrannon
Re: Problem with a binary search
A method, like compareTo(), cannot be called on a primitive. Imagine a[mid] = 5, then 5.compareTo( anything ) is not valid. You would simply use comparison operators, 5 < anything, 5 > anything, 5 == anything, etc.