我试图理解 binary search 错误与 byte
数组,我理解在计算 mid
索引时发生溢出的概念 . 但是,当我使用 byte
数组模拟相同的行为时,如下所示:
public byte binarySearch(byte[] arr, byte low, byte high, byte value){
if(low>high){
return -1;
}
/* Line 1 */ byte overflow_mid = (byte) (((byte) (low + high))/2); // This line giving overflow behaviour
/* Line 2 */ byte mid = (byte) ((low + high)/2); // however this line doesn't, which is not what i expected
if(arr[mid]== value){
return mid;
}
if(arr[mid]>value){
return binarySearch(arr, low, (byte) (mid-1), value);
}
return binarySearch(arr, mid, high, value);
}
我的直觉:
由于低和高变量的类型为 byte
,我相信在计算第2行的 mid index 时,它不需要再次显式转换为 byte
.
谢谢
2 回答
让我们说
byte low = 50, high = 100
.表达式
low + high
将首先将两者都提升为int
,然后添加它们,从而产生值150 (int)
.在版本1中,然后将
150 (int)
转换为byte
,其值为-106 (byte)
. Overflow . 与+
相同,/
运算符将双方都提升为int
,因此它变为-106 (int)
,除以2
时为-53 (int)
. 最后你再次投射到byte
,结尾是-53 (byte)
.在版本2中,您将
150 (int)
除以2
,并且由于双方都已经int
值,因此不会进行任何提升,最终会以75 (int)
结束 . 将其转换为byte
会给你75 (byte)
. No overflow .你投了两个非常不同的值 .
在第一行中,'re making two casts. The first one overflows. You'将
low + high
的结果重新转换为byte,在您的情况下溢出 .但是,在第二行中,您将
(low + high) / 2
转换为byte
,并假设low
和high
均为正值,这意味着结果r
必须为low < r < high
,因为low
和high
都可以由byte
变量表示,因此结果也是如此r
并且没有溢出 .