Reputation: 617
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])
{
}
Upvotes: 0
Views: 990
Reputation: 340763
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"};
Upvotes: 7
Reputation: 10372
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.
Upvotes: 2