二进制搜索C ++,STATUS_ACCESS_VIOLATION

时间:2014-04-13 05:25:21

标签: c++ vector binary-search

问题是我们第一次为矢量类做了二进制搜索功能,但我真的不知道为什么这不起作用。有谁知道什么可能是错的(当数字不在向量数组中时,状态访问违规)??

// size_是数组

中使用的元素的数量
  int Vector::bsearch(int value) const
  {
    int first = 0;
    int last = size_ - 1;
    int Substraction = size_ /2;

    while(last >= first)
    {
      Substraction = first + (last - first) / 2;

      if(array_[Substraction] > value)
        last = Substraction;

      else if(array_[Substraction] < value)
        first = Substraction;

      else if(array_[Substraction] == value)
        return Substraction;
    }
    return CS170::Vector::NO_INDEX;
  }

//解决

  int Vector::bsearch(int value) const
  {
    unsigned first = 0;
    unsigned last = size_ - 1;
    unsigned int mid;

    if(value < array_[0] || value > array_[size_ - 1])
      return CS170::Vector::NO_INDEX;

    while(last >= first)
    {
      mid = first + (last - first) / 2;

      if(value < array_[mid])
        last = mid - 1;

      else if(array_[mid] < value)
        first = mid + 1;

      else
        return mid;
    }
    return CS170::Vector::NO_INDEX;
  }

2 个答案:

答案 0 :(得分:1)

您不会在下一个循环之前排除刚刚测试过的元素。您选择的变量名称Subtraction是可怕的。它是中点

int first = 0;
int last = size_-1;
int mid = 0;

while(last >= first)
{
    mid = first + (last - first) / 2;

    if(value < array_[mid])
        last = mid-1; // don't include element just tested

    else if(array_[mid] < value)
        first = mid+1; // don't include element just tested

    else return mid;
}
return CS170::Vector::NO_INDEX

答案 1 :(得分:0)

您的初始化错误 -

int first = size_ - 1;
int last = first = 0;

应该是 -

int last = size_ - 1;
int first = 0;

此外,在while中,您应该使用以下条件 -

while (last>first)