简体   繁体   English

c中的二进制搜索算法

[英]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 the successor of k , if one exists, else return KEY_NOT_FOUND . 返回作为ksuccessor的键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 . tk后继 ,如果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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM