c++ - 二进制搜索算法 C++

标签 c++ function binary-search

我正在尝试编写一个函数,它接受一个整数数组并在数组的第一个和最后一个之间的部分搜索给定值。如果该值在数组中,则返回该位置。如果不是,我想返回-1。

这是我的函数的代码。

    int binarySearch(int *array, int min, int max, int value) {
    int guess = 0;
    bool found = false;
    while (!found) {
        guess = ((array[min] + array[max]) / 2);
        if (array[guess] == value) {
            found = true;
            return guess;
        }
        else if (array[guess] < value) {
            min = guess + 1;
        }
        else if (array[guess] > value) {
            max = guess - 1;
        }
    }
    return -1;
}

当您要搜索的值不在数组中时,我不确定如何跳出 while 循环?这是我为实现二进制搜索功能而遵循的伪代码:

  1. 让 min = 0 和 max = n-1(数组大小 -1 )。将猜测计算为最大值和 min,向下舍入(因此它是一个整数)。
  2. 如果数组[猜测]等于 目标,然后停止。你找到了!返回猜测。
  3. 如果猜测太 low,即array[guess] < target,则设min = guess + 1。
  4. 否则,猜测太高了。设置 max = guess - 1。
  5. 回到第 2 步。

最佳答案

我认为更改函数返回的内容是有意义的。与其返回 guess,不如在找到项目时返回有效索引,否则返回 -1。

此外,您正在使用 guess 作为值和索引。这肯定会引起问题。

是下面的一个值。

    guess = ((array[min] + array[max]) / 2);

猜想是下面的一个索引。

    else if (array[guess] < value) {

这是我的建议:

// Return the index if found, -1 otherwise.
int binarySearch(int *array, int first, int last, int value)
{
   // Terminating condition 1.
   // If first crosses last, the item was not found.
   // Return -1.
   if ( first > last )
   {
      return -1;
   }

   int mid = (first + last)*0.5;

   // Terminating condition 2.
   // The item was found. Return the index.
   if ( array[mid] == value )
   {
      return mid;
   }

   // Recurse
   if (array[mid] < value)
   {
      return binarySearch(array, mid+1, last, value);
   }
   else
   {
      return binarySearch(array, first, mid-1, value);
   }
}

关于c++ - 二进制搜索算法 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42214540/

相关文章:

python - Python中的二分搜索(二分法)

c++ - C 或 C++ 和 Linux 中的屏幕捕获程序

c++ - 在同一循环中集成 pthread_create() 和 pthread_join()

c++ - gdb 函数从本地范围调用 std::vector 导致错误

java - Codility 钉板

c++ - 对排序 vector 进行二分查找

c++ - GCC 规范文件 : how to get the installation path

c++ - QT中如何从文件中读取数据并显示在QEditText框中

c - 如何通过在 C 中传递多个参数的指针来调用函数?

function - Rust 中的默认函数参数