家人们能稍微详细解释一下为什么是-3而不是3吗

img

我是按照升序排的;

img


不排序的话,返回的下标是不准确, 如果数组中没有该元素则返回-1;
很高兴得到你的采纳

你再试一下 零, 壹, 这些字符看看结果是什么

Searches the specified array for the specified object using the binary
search algorithm. The array must be sorted into ascending order
according to the
{@linkplain Comparable natural ordering}
of its elements (as by the
{@link #sort(Object[])} method) prior to making this call.
If it is not sorted, the results are undefined.
(If the array contains elements that are not mutually comparable (for
example, strings and integers), it cannot be sorted according
to the natural ordering of its elements, hence results are undefined.)
If the array contains multiple
elements equal to the specified object, there is no guarantee which
one will be found.
看注释,写了字符串不能通过自然排序,结果是不确定的

另外,出现非-1的负数,代表插入位置的-(i+1),比如[1,2,4,5],查找3,那么得到-3,把它取反减1,得到的2代表3的插入索引。所以binarySearch不光能用于有序查找等值。还可以用于有序查插入位置。