简体   繁体   中英

Recursive binary search — Java

I've searched extensively online but all solutions I've found use two parameters to keep track of the size of the area being used. This would be easy if I was allowed to do that, but I'm not. As you can see below, the code lacks a stop value, because I have no idea how to retain the original information.

This is the code on Wikipedia, you can see they use imin and imax for tracker variables: http://en.wikipedia.org/wiki/Binary_search_algorithm#Recursive

My (very incorrect) code is below. The mid variable doesn't mean anything, because I don't know how to set low and high correctly if I'm not allowed to have any extra arguments in the function.

public static int findRecursiveB( String s, char c)
{
    int low = 0;             
    int high = s.length()-1;
    int mid = (low+high)/2; 

    if (s.charAt(mid) < c) {
        return findRecursiveB(s.substring(low, mid), c);
    }
    else if (s.charAt(mid) >= c) {
        return findRecursiveB(s.substring(mid+1, high), c);
    }
    else return mid;

}

One crucial point here is what does the original String s contain? For this to work, it has to be a sorted String, meaning that the characters in the String must be in order. Specifically, it looks like you've written code that expects s to be sorted in reverse order. Otherwise, unless I'm totally missing something, your code does exactly what it is supposed to: no need to pass extra params because you are passing in the substring on each recursive call.

Otherwise, good job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM