-
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;
}
}
-
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
Similar Threads
-
By mdengler in forum ASP.NET
Replies: 0
Last Post: 11-26-2002, 02:32 PM
-
Replies: 1
Last Post: 05-23-2002, 07:50 AM
-
Replies: 6
Last Post: 04-10-2002, 05:22 AM
-
Replies: 1
Last Post: 07-04-2001, 05:18 AM
-
By Tom Shreve in forum Enterprise
Replies: 0
Last Post: 04-07-2000, 08:15 PM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks