Jump to content

Java Binary Search


tombguy5

Recommended Posts

So after a few more projects, I've come across another problem, this time with a Java Binary Search Algorithm.

The goal is to open a .txt file with a bunch of random numbers and the program will ask you what you want to find and then display whether it is found or not. I have created the Algorithm, however, I need a way to call the method.

 

The solution may be somethign simple but I cannot find it.

 

Here is the code:

 

 

package searchingalgorithm;
 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
 
public class SearchingAlgorithm {
    
    public static void main(String[] args) throws IOException
    { 
        
    }
    
    private static long search(RandomAccessFile file, String target) throws IOException
    {
        /*
         * because we read the second line after each seek there is no way the
         * binary search will find the first line, so check it first.
         */
        System.out.println("Binary Search Working");
        file.seek(0);
        String line = file.readLine();
        if (line == null || line.compareTo(target) >= 0) {
            /*
             * the start is greater than or equal to the target, so it is what
             * we are looking for.
             */
            return 0;
        }
 
        /*
         * set up the binary search.
         */
        long beg = 0;
        long end = file.length();
        while (beg <= end) {
            /*
             * find the mid point.
             */
            long mid = beg + (end - beg) / 2;
            file.seek(mid);
            file.readLine();
            line = file.readLine();
 
            if (line == null || line.compareTo(target) >= 0) {
                /*
                 * what we found is greater than or equal to the target, so look
                 * before it.
                 */
                end = mid - 1;
            } else {
                /*
                 * otherwise, look after it.
                 */
                beg = mid + 1;
            }
        }
 
        /*
         * The search falls through when the range is narrowed to nothing.
         */
        file.seek(beg);
        file.readLine();
        return file.getFilePointer();
    }
    
}

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Forum Statistics

    11.1k
    Total Topics
    66.5k
    Total Posts
×
×
  • Create New...