0

I am trying to validate password and username using array and the array.BinarySearch function. The first two user names in the array: bradley and john are returning the correct position using the function 0 and 1. However when I try to validate the last two strings in the array jim and clarke, the binarySearch function returns the username is located at position -2 in the array both times which is causing validation to fail. Any ideas?

 String[] names = {"bradley","john","jim","clarke"};
    String[] passwords = {"password","password","test","test"};
    int pos = Arrays.binarySearch(names, uname);
                    System.out.println("Found you in array:" + uname + "here:" + pos);
                    if(pos >= 0)
                    {   
                        System.out.println("Validation password for:" + uname);
                        if(passwords[pos].equals(pword) && !loggedOn[pos])
                        {
    }

2 Answers 2

7

Your names array is not sorted:

String[] names = {"bradley","john","jim","clarke"};

which is a requirement of binarySearch() (and binary searching algorithm in general):

The range must be sorted into ascending order

Sort it first and it'll work like a charm:

String[] names = {"bradley","clarke","jim","john"};
Sign up to request clarification or add additional context in comments.

4 Comments

Binary search requires the values to be sorted so one can split an array range in the middle and decide on the middel value which half tobsplit further with.
Surely this will affect the validation of my password field then as it looks for the corresponding position in the password array which wont be the same if its sorted?
If you implement a manual sorting algorithm instead of a built-in, then you can swap the positions of the password array whenever you swap positions in the name array
@Bradley: of course, positions in passwords need to be in sync with names array. Which is the reason why you should rather have a custom User object with name and password fields. You'll also need a custom Comparator<User>. That being said, you should consider using Map from user name to password.
2

A binary search requires the array to be sorted before hand. You can either list the names in order, or perform the sorting yourself. You can use Arrays.sort(names) to sort the array of names.

1 Comment

it does merge sort internally ?

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.