折半查找(二分查找)

 表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。

 折半查找(二分查找)_第1张图片

#include 
#include 
#include 
#include 
using namespace std;
#define CNT 11

template
std::ostream& operator<<(std::ostream& cout, const std::vector& v)
{
	std::vector::const_iterator ite = v.begin();
	for (; ite != v.end(); ++ite)
	{
		cout << *ite << " ";
	}
	cout << std::endl;
	return cout;
}
// 二分查找,返回下标,不存在返回-1
int BinarySearch(std::vector& 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 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 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;
}

 

你可能感兴趣的:(算法)