user1686765 - 2 years ago 581

Java Question

Can I get some help please? I have tried many methods to get this to work i got the array sorted and to print but after that my binary search function doesnt want to run and give me right results. It always gives me -1. Any help?

`public class BinarySearch {`

public static final int NOT_FOUND = -1;

public static int binarySearch(double[] a, double key) {

int low = 0;

int high = a.length -1;

int mid;

while (low<=high) {

mid = (low+high) /2;

if (mid > key)

high = mid -1;

else if (mid < key)

low = mid +1;

else

return mid;

}

return NOT_FOUND;

}

public static void main(String[] args) {

double key = 10.5, index;

double a[] ={10,5,4,10.5,30.5};

int i;

int l = a.length;

int j;

System.out.println("The array currently looks like");

for (i=0; i<a.length; i++)

System.out.println(a[i]);

System.out.println("The array after sorting looks like");

for (j=1; j < l; j++) {

for (i=0; i < l-j; i++) {

if (a[i] > a[i+1]) {

double temp = a[i];

a[i] = a[i+1];

a[i+1] = temp;

}

}

}

for (i=0;i < l;i++) {

System.out.println(a[i]);

}

System.out.println("Found " + key + " at " + binarySearch(double a[], key));

}

}

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

you are not actually comparing with the array values. in

```
while (low <= high) {
mid = (low + high) / 2;
if (mid > key) {
high = mid - 1;
} else if (mid < key) {
low = mid + 1;
} else {
return mid;
}
}
```

Instead use this section

```
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] > key) {
high = mid - 1;
} else if (a[mid] < key) {
low = mid + 1;
} else {
return mid;
}
}
```

You were correct to find the indexes, but what you were doing is that you were just comparing index number with your key, which is obviously incorrect. When you write `a[mid]`

you will actually compare your key with the number which is at index `mid`

.

Also the last line of code is giving compile error, it should be

```
System.out.println("Found " + key + " at " + binarySearch(a, key));
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**