表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。
#include <iostream>
#include <vector>
#include <time.h>
#include <algorithm>
using namespace std;
#define CNT 11
template<typename T>
std::ostream& operator<<(std::ostream& cout, const std::vector<T>& v)
{
std::vector<T>::const_iterator ite = v.begin();
for (; ite != v.end(); ++ite)
{
cout << *ite << " ";
}
cout << std::endl;
return cout;
}
// 二分查找,返回下标,不存在返回-1
int BinarySearch(std::vector<int>& v,double val)
{
if (v.empty()) return -1;
if (!std::is_sorted(v.begin(), v.end()))
std::sort(v.begin(), v.end());
int findCnt = 1;
int left = 0,right = v.size() - 1,mid;
while (left <= right)
{
mid = left + (right - left) / 2;
std::cout << "第" << findCnt++ << "次查找,找到" << v[mid];
if (v[mid] == val)
{
std::cout << "是目标值,停止查找!" << std::endl;
return mid;
}
else if (v[mid] > val)
{
std::cout << ",比目标值大,继续向左查找!" << std::endl;
right = mid - 1;
}
else
{
std::cout << ",比目标值小,继续向右查找!" << std::endl;
left = mid + 1;
}
}
return -1;
}
int main()
{
srand(unsigned(time(NULL)));
std::vector<int> v;
std::cout << "排序前的序列为:";
for (int i = 0; i < CNT; ++i)
{
v.push_back(rand() % 100);
}
std::cout << v;
int findNum = v.front();
std::sort(v.begin(),v.end());
std::cout << "排序后的序列为:";
std::cout << v;
std::vector<double> findNumVec;
findNumVec.push_back(findNum);
findNumVec.push_back(1.1111);
for (int i = 0; i < 2; ++i)
{
std::cout << "查找目标值:" << findNumVec[i] << std::endl;
int idx = 0;
if ((idx = BinarySearch(v, findNumVec[i])) != -1)
{
std::cout << "在下标为 " << idx << " 处找到 " << findNumVec[i] << std::endl;
}
else
std::cout << "不存在 " << findNumVec[i] << std::endl;
}
return 0;
}