Array.binarySearch returning wrong data

雨燕双飞 提交于 2019-12-02 14:31:07

问题


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])
                        {
    }

回答1:


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"};



回答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.



来源:https://stackoverflow.com/questions/13732413/array-binarysearch-returning-wrong-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!