zoukankan      html  css  js  c++  java
  • Binary Search二分法搜索C++程序

    二分法基本上学计算机的都听过,但是有人不知道的就是其实二分法是减治法的思想。

    所谓减治法和分治法有一个主要差别就是减治法是减去一般,就是分治之后只需要解决原问题的一半就可以了得到全局问题的解了。所以速度很快。

    下面是二分法的递归程序和非递归程序和主测试程序:

    #include<iostream>
    #include<vector>
    using namespace std;
    
    template<typename T>
    int recurBiSearch(const vector<T> &vt, T key, int low, int up)
    {
    	if(low>up) return -1;
    	int mid = (low+up)>>1;
    	if (key < vt[mid])
    	{
    		return recurBiSearch(vt, key, low, mid-1);
    	}
    	else if (vt[mid] < key)
    	{
    		return recurBiSearch(vt, key, mid+1, up);
    	}
    	return mid;
    }
    
    template<typename T>
    int iterBiSearch(vector<T> &vt, T key, int low, int up)
    {
    	int mid;
    	while (low<=up)
    	{
    		mid = (low+up)>>1;
    		if(key<vt[mid])
    			up = mid - 1;
    		else if(vt[mid]<key)
    			low = mid + 1;
    		else return mid;
    	}
    	return -1;
    }
    
    int main()
    {
    	std::vector<int> vec;
    
    	// set some initial content:
    	for (int i=1;i<10;i++) vec.push_back(i<<2);
    
    	vec.resize(7);
    	vec.resize(12,80);
    
    	std::cout << "vec contains:";
    	for (int i=0;i<vec.size();i++)
    		std::cout << ' ' << vec[i];
    	std::cout << '
    ';
    
    	//二分法特征:这里vec.size()-1和不减1都是可以的。
    	cout<<"Recurrence Search Index Position: ";
    	int ind = recurBiSearch(vec, 20, 0, vec.size()-1);
    	cout<<ind;
    	cout<<"	Value: "<<vec[ind]<<endl;
    
    	cout<<"Iterative Search Index Position: ";
    	ind = iterBiSearch(vec, 20, 0, vec.size()-1);
    	cout<<ind;
    	cout<<"	Value: "<<vec[ind]<<endl;
    
    	system("pause");
    	return 0;
    }

    运行结果:


  • 相关阅读:
    codevs 3160 最长公共子串
    bzoj1593 [Usaco2008 Feb]Hotel 旅馆
    bzoj1230 [Usaco2008 Nov]lites 开关灯
    洛谷P1558 色板游戏
    洛谷P2253 好一个一中腰鼓!
    洛谷P2345 奶牛集会
    TopCoder SRM420 Div1 500pt RedIsGood
    洛谷P3144 [USACO16OPEN]关闭农场Closing the Farm_Silver
    洛谷P1455 搭配购买
    洛谷P2398 GCD SUM
  • 原文地址:https://www.cnblogs.com/suncoolcat/p/3423959.html
Copyright © 2011-2022 走看看