I dont know if the functionality of my code is the correct one for binary search BUT this is not my question, I want to solve it myself.
My problem is in testing its functionality while I get the following errors:
I really dont know how to solve this issue. Please help me!
My code:
public class BinarySearchGeneric<T extends Comparable<T>>{
public int search(T[] array, T element){
int start = 0;
int end = array.length - 1;
int mid = (start + end) / 2;
while(!element.equals(array[mid]) && end != 0) {
if (element.equals(array[mid])) {
return mid;
} else if (array[mid].compareTo(element) < 0) {
end = mid - 1;
mid = (start + end) / 2;
} else if(array[mid].compareTo(element) > 0){
start = mid + 1;
mid = (start + end) / 2;
}
}
return -1;
}
}
Main Method:
public class Main {
public static void main(String[] args) {
int[] a = {1,2,3,4,5,6,7,8,9,10};
BinarySearchGeneric binarySearchGeneric = new BinarySearchGeneric(a);
System.out.println("BinarySearch Generic: " + binarySearchGeneric.search(a, 8));
}
}
There are two compilation issues here:
There is no constructor of BinarySearchGeneric
which takes a parameter, but you're trying to pass the parameter. Remove it:
BinarySearchGeneric binarySearchGeneric = new BinarySearchGeneric();
int[]
is not an acceptable parameter to a generic method expecting an array, because int
is a primitive type, not a reference type, and so can't be used in generics. The solution is simply to declare an array of Integer
, rather than int
:
Integer[] a = {1,2,3,4,5,6,7,8,9,10};
The compiler converts these int literals to Integer
instances automatically.
But there are more issues.
You're declaring a variable of raw type. This basically switches off the compiler's type checking associated with that variable, making it likely that you will make a type error. Add the generic parameters:
BinarySearchGeneric<Integer> binarySearchGeneric = new BinarySearchGeneric<>();
Arrays and generics don't really play well together. Things would start get a bit messy if you declared a generic, comparable class:
class GenericComparable<T> extends Comparable<T> { ... }
and then tried to declare an array of GenericComparable
s to pass to binarySearchGeneric
, since you can't directly create a generic array.
It's much easier simply to avoid arrays, and use a List<T>
instead:
public int search(List<T> array, T element){
Potentially, you have inconsistent behaviour, because you are mixing equals
and compareTo
in the search. Whilst compareTo
should be consistent with equals
(in the sense that a.compareTo(b) <=> a.equals(b)
, it isn't necessarily true.
You can make the behaviour consistent by only using compareTo
:
int c = array[mid].compareTo(element);
if (c == 0) {
// ...
} else if (c < 0) {
// ...
} else {
// ...
}