Reputation: 11
I need to use binary search to locate 45.3 in the array. Here's what I have so far.
public class Bsearch {
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] = { 10, -3, 5, 24, 45.3, 10.5 };
System.out.println("45.3 Found" + binarySearch(a, 45.3));
}
}
All my errors seem to be stemming from this area-
int [] a = new Integer [ SIZE ]={ 10,-3,5,24,45.3,10.5 };
System.out.println("45.3 Found" +binarySearch(a, 45.3));
All this is new to me so sorry for any obvious mistakes.
Upvotes: 1
Views: 1549
Reputation: 31299
The problem is indeed in this line:
int[] a = new Integer[SIZE] = { 10, -3, 5, 24, 45.3, 10.5 };
There are a number of issues:
Integer[]
to an int[]
variable. Change it to new int[]
new
operator, you either specify size of the array, or the contents.So either:
int[] a = new int[SIZE];
Or
int[] a = new int[] { 10, -3, 5, 24, 45, 10 };
Both will work.
You have to decide whether you want to use primitive types (int
) of class wrappers (Integer
) and stick to it.
Your method binarySearch
takes an int[]
as a parameter, but you are using methods (compareTo
) that are only available on Integer
.
But actually, comparing is much simpler with primitive types:
if (a[mid] < x)
low = mid + 1;
else if (a[mid] > x)
high = mid - 1;
else
return mid;
Upvotes: 1
Reputation: 338
For binary search Data Array should be sorted, and sorted in the right order, but the array you are passing to binarySearch(int[] a, int x) is not sorted so first sort the array and then apply binary search on it. Also check your logic for binary search, you are comparing middle element with 0 it should be compared with the element to be searched(key)
while(high >= low) {
int middle = (low + high) / 2;
if(data[middle] == key) {
return true;
}
if(data[middle] < key) {
low = middle + 1;
}
if(data[middle] > key) {
high = middle - 1;
}
}
Upvotes: 1