Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Getting an int when using Comparable object

Trying to get an understanding of the binary search-ultimately I want to return the index where a new item would be inserted in the array. Taking small steps, I thought I would first see if I could get the item found index out of the array; meaning if the item is found it would print out the index position. However, when using Comparable it seems more of a challenge because int is a primative type. So far, i've managed to figure out that the
Integer indexOf = new Integer( 5 ); really isn't doing anything.
Any suggestions?

import java.lang.*;

public class BinaryIndex{

public static void main ( String args[] ){

String objArray[] = { "a", "c", "e", "f", "g", "h", "i" };
String searchObj = "c";
binarySearch( objArray, searchObj);
System.out.println("Return the index of the insert point." );

System.out.println( "End of program" );
}

public static int binarySearch( Comparable[] objArray, Comparable searchObj )
{
int low = 0;
int high = objArray.length - 1;
int mid = 0;
Integer indexOf = new Integer( 5 );

while (low <= high )
{
mid = ( low + high ) / 2;
if (objArray[mid].compareTo( searchObj) < 0 )
low = mid + 1;
else if ( objArray[mid].compareTo( searchObj ) > 0 )
high = mid - 1;
else
return mid;
System.out.println( indexOf.intValue());

}
// item not found
System.out.println( "Item Not Found" );
return -1;
}

}
[1705 byte] By [JavaBeanie] at [2007-11-11 6:54:14]
# 1 Re: Getting an int when using Comparable object
Actually, I figured this one out myself. I got rid of
Integer indexOf = new Integer( 5 ); -- and --
System.out.println( indexOf.intValue()); since they were useless
Then in my main method changed
binarySearch( objArray, searchObj); -- to --
int insertPoint = binarySearch( objArray, searchObj);

and viola
JavaBeanie at 2007-11-11 22:40:04 >