c++ - 实现二分查找

标签 c++ algorithm binary-search

<分区>

这是我的二进制搜索:

int binarySearch(int arr[], int value, int min, int max){
  int pos = -1;

  while (max >= min && pos == -1) {
    int mid = (max+min)/2;

    if(arr[mid] ==  value){
      pos = mid;
    }else if(arr[mid] < value){
      min = mid +1;
    }else if(arr[mid] > value){
      max = mid -1;
    }

  }
  return pos;
}

我这样调用它:

 //Arr contain values 0-63
int i = binarySearch(arr, 64, 0, 64);

这些是中间值

32 48 56 60 62 63 64

在最后一次检查时,当数组中的最后一个位置是 63 时,我尝试访问位置 64 的元素。

我的实现有什么问题?

最佳答案

您的数组包含 0-63 的值(如您所述),并且您为最小值和最大值指定了以下值:最小值 = 0,最大值 = 64。并更改以下行,以便您的代码可以处理高 int 值,否则可能会出现内存溢出。

       int mid = min+(max-min)/2;

上述公式简化为 (max+min)/2 本身但保护整数溢出。

关于c++ - 实现二分查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13112124/

相关文章:

c++ - 为什么 std::inserter 这么慢?

c++ - 在使用 boost::fusion 迭代时将 pretty-print 绑定(bind)到 boost::phoenix actors

c++ - 这段代码线程安全吗?如果不是什么时候以及怎么会出错?

algorithm - 在文档中查找个人信息(难题)

c++ - 算法库

algorithm - Clog n的一个算法问题的设计[C++代码]

c++ - Windows API MONITORINFO 结构

c++ - 快速排序实现错误

algorithm - 最小化任何相邻站之间的最大距离

algorithm - 最大子数组和模 M