java left logo
java middle logo
java right logo
 

Home
 
 
Main Menu
Home
Java Tutorials
Book Reviews
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Java Network
Java Forums
Java Blog




Most Visited Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews
Top Rated Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews


Statistics
Registered Users: 4100
Java SE Tips: 614
Java ME Tips: 202
Java EE Tips: 183
Other API Tips: 779
Java Applications: 298
Java Libraries: 209
Java Games: 16
Book Reviews:
 
 
 
Recursive Binary Search Implementation in Java E-mail
User Rating: / 53
PoorBest 

This tip shows how to implement binary search recursively in Java.

public class BinarySearchRecursive
{
    public static final int NOT_FOUND = -1;

    /**
     * Performs the standard binary search
     * using two comparisons per level.
     * This is a driver that calls the recursive method.
     @return index where item is found or NOT_FOUND if not found.
     */
    public static int binarySearchComparable [ ] a, Comparable x )
    {
        return binarySearcha, x, 0, a.length -);
    }

    /**
     * Hidden recursive routine.
     */
    private static int binarySearchComparable [ ] a, Comparable x,
                                     int low, int high )
    {
        iflow > high )
            return NOT_FOUND;

        int mid = low + high 2;

        ifamid ].compareTo)
            return binarySearcha, x, mid + 1, high );
        else ifamid ].compareTo)
            return binarySearcha, x, low, mid - );
        else
            return mid;
    }

    // Test program
    public static void mainString [ ] args )
    {
        int SIZE = 8;
        Comparable [ ] a = new Integer SIZE ];
        forint i = 0; i < SIZE; i++ )
            anew Integeri * );

        forint i = 0; i < SIZE * 2; i++ )
            System.out.println"Found " + i + " at " +
                                     binarySearcha, new Integer) ) );
    }
}

 Related Tips

 
< Prev   Next >

Page 1 of 0 ( 0 comments )

You can share your information about this topic using the form below!

Please do not post your questions with this form! Thanks.


Name (required)


E-Mail (required)

Your email will not be displayed on the site - only to our administrator
Homepage(optional)



Comment Enable HTML code : Yes No



 
       
         
     
 
 
 
   
 
 
java bottom left
java bottom middle
java bottom right
RSS 0.91 FeedRSS 1.0 FeedRSS 2.0 FeedATOM FeedOPML Feed

Home - About Us - Privacy Policy
Copyright 2005 - 2008 www.java-tips.org
Java is a trademark of Sun Microsystems, Inc.