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

📄 binarysearch.cpp

📁 这是数据结构、算法与应用-C++语言描述的代码
💻 CPP
字号:
// binary search

#include <iostream>
#include <algorithm>

using namespace std;

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

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

⌨️ 快捷键说明

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