⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bsearch.cpp

📁 data structures, algorithms and Application书的源代码
💻 CPP
字号:
// binary search

#include <iostream.h>

template<class T>
int BinarySearch(T a[], const T& x, int n)
{// Search a[0] <= a[1] <= ... <= a[n-1] for x.
 // Return position if found; return -1 otherwise.
   int left = 0; int right = n - 1;
   while (left <= right) {
      int middle = (left + right)/2;
      if (x == a[middle]) return middle;
      if (x > a[middle]) left = middle + 1;
      else right = middle - 1;
      }
   return -1; // x not found
}

void main(void)
{
   int a[7] = {0, 2, 3, 4, 6, 7, 9};
   cout << BinarySearch(a, 4, 7) << endl;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -