欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二分查找:比较次数

程序员文章站 2022-03-01 18:44:02
...
#include <iostream>
#include<algorithm>
#include<vector>
#include<fstream>
using namespace std;

#define see(x) cout<<x<<endl

class Sol
{
public:
	Sol() {}
	Sol(int search):m_goal(search), m_CmpTimes(0)m_pos(0)
	{
		readInfo();
	}
	~Sol() {}


	void readInfo() {
		//"C:\\Users\\dell\\source\\repos\\find_ci_xu\\Main\\test.txt"
		fstream fin("test.txt", ios::in);
	
		while (!fin.eof()) {
			int num;
			fin >> num;
			m_nums.push_back(num);
		}

		fin.close();
	}


	void showAns() {
		if(countCmpTimes(0, m_nums.size()-1))
		printf_s("arr[%d]=%d, cmpTimes= %2d\n",m_pos,m_goal, m_CmpTimes);
		else {
			printf_s("cmpTimes= %2d,not find %d.\n",m_CmpTimes,m_goal);
		}
	}
	bool countCmpTimes(int i, int j) {
		bool succ = false;
		while (!succ&&i <= j) {
			int mid = (i + j)/2;
			if (m_nums.at(mid) == m_goal) {
				m_pos = mid + 1;
				succ = true;
			}
			else if (m_nums.at(mid) < m_goal) {
				i=mid+1;
			}
			else {
				j=mid - 1;
			}
			m_CmpTimes++;
			
		}
		return succ;
	}
private:
	vector<int> m_nums;
	int m_CmpTimes,m_goal,m_pos;
};



int main()
{
	int num;
	int times = 9;
	while (times--) {
		cin >> num;
		Sol test(num);
		test.showAns();
	}
	
	system("pause");
	return 0;
}


相关标签: 算法的乐趣