【发布时间】:2016-04-05 05:28:44
【问题描述】:
我试图理解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);
}
我的直觉:
由于 low 和 high 变量的类型为 byte,我相信它不需要在第 2 行计算 mid index 时再次显式转换为 byte。
谢谢
【问题讨论】:
-
为什么将
byte用于low和high?它们是索引值,而不是数组的值,所以只需使用int就不会出现任何溢出问题,而且它将消除对所有这些 dang casts 的需要。无论如何,数组索引值都会提升为int(请参阅JLS 15.13 Array Access Expressions),因此您并没有真正节省任何东西。 -
是的,你是绝对正确的,但我试图通过使用字节索引和字节数组模拟整数行为来理解这个错误,所以我希望它会崩溃。只是出于好奇。
标签: java algorithm debugging byte binary-search-tree