[英]Binary search algorithm in c
I'm trying to create a function int find_pos(int item, int a[], int len)
that works as follows: 我正在尝试创建一个函数
int find_pos(int item, int a[], int len)
,其工作方式如下:
Returns the index in array of the key
t
that is the thesuccessor
ofk
, if one exists, else returnKEY_NOT_FOUND
.返回作为
k
的successor
的键t
数组中的索引(如果存在),否则返回KEY_NOT_FOUND
。
Key t
is the successor of k
, if t
is the smallest key stored in sda->buffer
such that t >= k
. 键
t
是k
的后继 ,如果t
是存储在sda->buffer
的最小键,则t >= k
。
const int KEY_NOT_FOUND = -1;
int find_pos(int item, int a[], int len) {
int low = 0;
int high = len-1;
if (a[0] >= item && len == 1) {
return 0;
}
if(a[0] < item && len == 1) {
return KEY_NOT_FOUND;
}
while (low <= high) {
int mid = low + (high - low) / 2;
if (a[mid] == item) {
return mid;
} else if (a[mid] < item) {
low = mid + 1;
} else {
high = mid - 1;
}
if(a[high] < item) {// invalid size read of 4
return high + 1;
}
}
return KEY_NOT_FOUND;
}
However, it may cause invalid read size read of 4 at 但是,它可能导致读取4的无效读取大小
if(a[high] < item)
Can somone explain(or give an example) why does this line cause invalid read size read of 4? 可以解释(或给出一个例子)为什么这一行导致无效的读取大小读取为4? Thanks in advance.
提前致谢。
Let's say low
==
high
==
0
the start of the while loop. 假设
low
==
high
==
0
while循环的开始。
So, mid
==
0
所以,
mid
==
0
Then the code does high = mid - 1;
然后代码
high = mid - 1;
So, high
is now negative, and a[high]
is an illegal access. 因此,现在
high
,现在是负面的,而a[high]
是非法访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.