// BSearch.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
template <class T>
void PrintfNum(T a[],const int& n);
/**
* search n in a[], return the index, if not find, return -1.
*/
template <class T>
int BSearch(T a[],const int& length,const int& n){
int left = 0, right = length - 1;
while(left <= right){
int middle = (left + right) / 2;
//cout << "middle:" <<middle << " ,left:" << left << " ,right:" << right << endl;
if(n < a[middle]){
right = middle - 1;
}else if(n > a[middle]){
left = middle + 1;
}else{
return middle;
}
}
return -1;
}
/**
* A better one
* search n in a[], return the index, if not find, return -1.
*/
template <class T>
int BetterBSearch(T a[],const int& length,const int& n)
Binary Search 二分查找,二分搜索 C++
最新推荐文章于 2024-02-19 17:01:40 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)