查找顺序数组中元素第一次出现的位置(二分查找)

本文探讨编程珠玑中的一道题目,通过二分查找算法高效地找出元素在有序数组中第一次出现的位置,涉及搜索、距离计算、向量操作和迭代器的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编程珠玑第4章第2题

#include "stdafx.h"
#include 
#include 
using namespace std;

template
bool IsSorted( InPtr posBegin_, InPtr posEnd_ )
{
	InPtr posSecond = posBegin_;
	++posSecond;
	for( ;posSecond != posEnd_; ++posSecond)
	{
		if( *posSecond < *posBegin_ )
		{
			return false;
		}
		++posBegin_;
	}
	return true;
}

template
InPtr BinarySearchFirst( InPtr posBegin_, InPtr posEnd_, const TYPE Search_ )
{
	int iDistance = distance(posBegin_, posEnd_);
	if( iDistance <= 0 )
	{
		return posEnd_;
	}

	InPtr posLeft = posBegin_;
	InPtr posRight = posEnd_;
	InPtr posMiddle = posBegin_;
	advance(posMiddle, iDistance / 2);
	InPtr posFind;
	if( *posMiddle > Search_ )
	{
		/// 当中间位较大时,在前半部寻找
		posRight = posMiddle;
		posFind = BinarySearchFirst( posLeft, posRight, Search_ );
	}
	else if( *posMiddle < Search_ )
	{
		/// 当中间位较大时,在后半部寻找
		posLeft = posMiddle;
		advance( posLeft, 1 );
		posFind = BinarySearchFirst(posLeft, posRight, Search_ );
	}
	else
	{
		/// 当找到的是第一个时,返回
		if( posMiddle == posBegin_ )
		{
			return posMiddle;
		}

		/// 当找到的前一个与当前不等时,返回
		InPtr posPrev = posMiddle;
		advance(posPrev, -1);
		if( *posPrev != Search_ )
		{
			return posMiddle;
		}

		/// 否则在前半部寻找
		posRight = posMiddle;
		posFind = BinarySearchFirst(posLeft, posRight, Search_ );
	}

	if( posFind != posRight )
	{
		return posFind;
	}
	return posEnd_;
}

int _tmain(int argc, _TCHAR* argv[])
{
	vector coll;
 	for(int i = 0; i < 20; ++i)
 	{
 		coll.push_back(i);
 	}

	if( !IsSorted(coll.begin(), coll.end()) )
	{
		cout << "未排序!" << endl;
		return 0;
	}
	vector::iterator pos;
	int iFind = 0;
	pos = BinarySearchFirst(coll.begin(), coll.end(), iFind);
	if( pos != coll.end() )
	{
		cout << "在第" << distance(coll.begin(), pos) << "位发现"
			<< "元素" << iFind << endl;
	}
	else
	{
		cout << "未找到元素" << iFind << endl;
	}
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值