Array.binarySearch returning wrong data

前端 未结 2 1560
遇见更好的自我
遇见更好的自我 2021-01-26 03:31

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

相关标签:
2条回答
  • 2021-01-26 03:43

    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"};
    
    0 讨论(0)
  • 2021-01-26 04:05

    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.

    0 讨论(0)
提交回复
热议问题