C/C++:迭代器的簡單二分查找

I just don't want to regret it !




#include <iostream>
#include <algorithm>
#include <string>
#include <vector>

using namespace std;

int main()
{
	vector<int>c{1, 2, 3, 4, 5};//默認排好了序
	
	auto beg = c.begin();auto end = c.end();//搜索範圍
	auto mid = c.begin() + (end - beg) / 2;//初始中間點
	auto aim = 3;//目標值

	while (mid != end && *mid != aim)
	{
		if (aim < *mid){
			end = mid;
		}//前半部分
		else{
			beg = mid + 1;
		}//後半部分
		mid = beg + (end - beg) / 2;//處理尋找之後的mid值
	}

	if (*mid == aim){
		cout << "Yes" << endl;
	}
	else{
		cout << "No" << endl;
	}

	system("pause");
	return 0;
} 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章