Search code examples
javaobjectbinary-search

Binary search with objects


I needed to use binary search on an array to find their indexes. I was able to do that, however I now need to use Objects with the array being of type Integer instead of int.

Here's the question : "Supply the code for the binarySearch method remembering that the parameters it receives are Object type objects, and if either is used to call the compareTo method, it must first be cast as a Comparable or original object type."

I would really appreciate if I got some more info on this if not the code for it. The question confused me a bit.

this is the type of data passed to the binary search method.

int i[] = {-7, 15, 21, 22, 43, 49, 51, 67, 78, 81, 84, 89, 95, 97};
    Integer iw[] = new Integer[14];
    for(int k = 0; k < 14; k++)
    {
        iw[k] = i[k];
    }
private static int binarySearch(Object a[], Object srchVal)
{
//binary search code
}

Solution

  • For comparing objects, you can call the compareTo function, if the object has implemented the Comparable interface.

    The Comparable interface in java has a method public int compareTo(Object obj) which returns a positive integer if caller object is greater than object passed to method, negative integer if caller is lesser, and zero if they are same.

    You can get more information here (for Java 8): https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html

    As for your problem, they are asking you to cast the Object passed to one that has implemented the Comparable interface. You can cast it to Integer(original object type) or any user defined class that implements Comparable and has compareTo method defined.

    Here is how I wrote the function. I cast the Object to Integer as Integer object has a default implementation of compareTo function.

    public static int binarySearch(Object a[], Object srchVal)
    {
        
        int l = 0, h = a.length-1, mid;
        while(l <= h) {
            mid = l + (h - l)/2;
            if( ((Integer)a[mid]).compareTo((Integer) srchVal) == 0  ) {
                return mid;
            }
            else if( ((Integer)a[mid]).compareTo((Integer) srchVal) < 0 ) {
                l = mid + 1;
            }
            else {
                h = mid - 1;
            }
        }
    
        return -1;
    }