1. 程式人生 > >二分法求單峰函式最大值

二分法求單峰函式最大值

#include <iostream>
#include <boost/timer/timer.hpp>
#include <ctime>
#include <set>
using namespace boost::timer;
using namespace std;

int recursive_unimodal(int *a,int low,int high)//二分法,找最大值
{
	if(low<high){
		int mid=(low+high)>>1;
		int lowValue=recursive_unimodal(a,low,mid);
		int highValue=recursive_unimodal(a,mid+1,high);
		if(lowValue>highValue)
			return lowValue;
		else
			return highValue;
	}
	return a[low];
}


int iterator_unimodal(int *a,int low,int high)
{
	while(low<high){
		int mid=(low+high)>>1;
		if(a[mid]>a[mid+1]){
			high=mid;
		}else{
			low=mid+1;
		}
	}
	return a[low];
}



int main()
{
	srand(time(NULL));
	int num1;
	while ((num1=rand()%100)<70);
	int num2;
	while ((num2=rand()%100)<70);

	set<int> s1;
	for(int i=0;i<num1;++i){
		s1.insert(rand()%10001-5000);
	}

	num1=s1.size();
	int *a=new int[num1];
	set<int>::iterator ite=s1.begin();
	for(int i=0;i<num1;++i){
		a[i]=*ite;
		++ite;
	}


	set<int> s2;
	for(int j=0;j<num2;++j){
		int te=rand()%10001-5000;
		
		bool flag=true;
		while (flag){
			for(int i=0;i<num1;++i){
				if(te==a[i]){
					te=rand()%10001-5000;
					flag=true;
					break;
				}
			}	
			flag=false;
		}
		s2.insert(te);
	}
	
	num2=s2.size();

	int *c = new int[num1+num2];
	int index=0;
	set<int>::iterator iter1=s1.begin();
	while (iter1!=s1.end()){
		c[index++]=*iter1;
		++iter1;
	}
	set<int>::reverse_iterator iter2=s2.rbegin();
	while (iter2!=s2.rend()){
		c[index++]=*iter2;
		++iter2;
	}
	
	for(int k=0;k<num1+num2;++k){
		std::cout<<c[k]<<" ";
	}
	std::cout<<endl;
	delete[]a;
	
	cpu_timer t1;
	t1.start();
	int result=recursive_unimodal(c,0,num2+num1);
	t1.stop();
	cout<<result<<endl;
	cout<<t1.format();

	cpu_timer t2;
	t2.start();
	int result2=iterator_unimodal(c,0,num2+num1);
	t2.stop();
	cout<<result2<<endl;
	cout<<t2.format();
	
	delete[]c;

}