0

I want to know how to do binary search on character array in java

There is a in-build function in java , but i don't want to use that , any help or pointers will be really appreciated.

I just started with below as i know binary search needs the array to be sorted

char[] whitelist = {'f','e','d','c','b','a'};

                Arrays.sort(whitelist);

                for (char ch : whitelist) {  
                    System.out.println("The values after sorting\n"+ch);
                }
3
  • I doubt that you really need help with google or SO's search functionality. Commented Sep 20, 2011 at 6:00
  • If the array is sorted then you dont need to actually "search" it, if you want "f" then just count how far away f is from a and access the index of the whitelist at that position. Commented Sep 20, 2011 at 6:01
  • 1
    AntonioP I'm guessing he wants a system that will work even when he's not just spelling out the whole alphabet. :) Commented Sep 20, 2011 at 6:04

1 Answer 1

3

As simple as Java does:

int binarySearch(char[] a, char key) {
    int low = 0;
    int high = a.length - 1;

    while (low <= high) {
        int mid = (low + high) >>> 1;
        char midVal = a[mid];

        if (midVal < key)
            low = mid + 1;
        else if (midVal > key)
            high = mid - 1;
        else
            return mid; // key found
    }
    return -(low + 1);  // key not found.
}

Of course, replace the array a with your array, i.e. whitelist.

Basically, look out for this - http://en.wikipedia.org/wiki/Binary_search_algorithm#Iterative

Sign up to request clarification or add additional context in comments.

7 Comments

Especially for beginners it's good style to have properly indented code.
@kobe - No problems. This should work, since this is pretty much what is done by the in-built API as well. Generally, if you intend to implement an API on your own, it is good to see (in fact, leverage) the in-built API's source itself, to start with.
@Saket - this is HOMEWORK. It is bad form to provide a potted answer that the OP can simply copy and paste ... as he is apparently doing. The point of homework is to get the student to do the work, and learn in the process. Giving him/her potted answers defeats the purpose.
(this is more or less copy/pasted from Arrays#binarySearch0)
@StephenC ,@andreas , I went through the logic and understood now , as you suggested i won't copy as it is.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.