I am currently in a class for Java Programming and am completely new to Java. I am trying to create a program that will use binary search for the value 45.3
class findValue {
public static void main(String args[]) {
double a[] = new double[6]; //declaration
a[0] = -3; //initialization
a[1] = 10;
a[2] = 5;
a[3] = 24;
a[4] = 45.3;
a[5] = 10.5;
int n = a.length; //storing length of array
int temp = 0; //declaring temporary storage place
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (a[j - 1] > a[j]) {
temp = (int)a[j - 1];
a[j - 1] = a[j];
a[j] = temp; //bubble sorting
};
};
};
System.out.println("45.3 found" + binarySearch(a, 45.3));
};
public static void binarySearch(Integer[] a, int x) {
int low = 0;
int high = a.length - 1;
int mid; //values for binary search
while (low <= high) {
mid = (low + high) / 2; //setting value for searching
if (a[mid].compareTo(x) < 0) {
low = mid + 1;
}
else if (a[mid].compareTo(x) > 0) {
high = mid - 1;
};
};
};
This is the compiler error I got:
Line: 25
method binarySearch in class findValue cannot be applied to given types;
required: java.lang.Integer[],int
found: double[],double
reason: actual argument double[] cannot be converted to java.lang.Integer[] by method invocation conversion
(I know there is a lot of room for improvement, but I'm just suggesting the minimum number of changes for the program to work)
The method
public static void binarySearch(Integer[] a, int x) {...}
is expecting integers, but we want it to use doubles insted. This means that the arguments should be an array of doubles, and the double to find:
public static void binarySearch(double[] a, double x) {...}
This said, we know that this function will return an int, so we set the return type:
public static double binarySearch(double[] a, double x) {...}
Now, finally, we must return the number we were looking for by adding the following at the end of the method (after the while):
return mid;
The final result should be:
class findValue {
public static void main(String args[]) {
double a[] = new double[6]; //declaration
a[0] = -3; //initialization
a[1] = 10;
a[2] = 5;
a[3] = 24;
a[4] = 45.3;
a[5] = 10.5;
int n = a.length; //storing length of array
int temp = 0; //declaring temporary storage place
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (a[j - 1] > a[j]) {
temp = (int)a[j - 1];
a[j - 1] = a[j];
a[j] = temp; //bubble sorting
}
}
}
System.out.println("45.3 found: " + binarySearch(a, 45.3));
}
public static int binarySearch(double[] a, double x) {
int low = 0;
int high = a.length - 1;
int mid = (low + high) / 2; //values for binary search
while (low <= high) {
mid = (low + high) / 2; //setting value for searching
if (Double.compare(a[mid], (double)x) < 0) {
low = mid + 1;
}
else if (Double.compare(a[mid], (double)x) > 0) {
high = mid - 1;
}
}
return mid;
}
}
Output:
45.3 found: 5