Searching in an array with custom comparator in java

前端 未结 4 1698
醉酒成梦
醉酒成梦 2021-01-17 00:58

Why does it always return 49999 no matter what strToSearch variable holds? Even with the clank search variable it returns the same. Have I missed s

4条回答
  •  旧巷少年郎
    2021-01-17 01:13

    The JavaDoc on Arrays.binarySearch(...) states that the array must already be sorted and thus the comparator actually compares the array value and the search string and not is not used for sorting the array again.

    This means you get something like compare(arr[x], "12") and your if condition states that both strings must contain a comma, otherwise they are equal. And "12" doesn't contain any commas, thus making "12" equal to every element in the array (always returns 0).

    Edit:

    Looking at the source code seems to support my assumption. There's this line, for example:

     //c is the Comparator
     //midVal is an element of your array 
     //key is the key parameter you passed to binarySearch(...)
     c.compare(midVal, key); 
    

    The reason for 49999 being returned is that the first mid value is at index mid = (low + high) >> 1 which is (0 + 99999) >> 1 == 49999 and since the comparator returns 0 the values are considered equal. And boom, the value is "found".

提交回复
热议问题