较快速在一个数组中查找最大值和最小值(2)

/*分治法*/
#include<iostream>
#include<string>
#include<vector>
#include<fstream>
using namespace std;
int a[16]={1,3,5,7,9,11,14,2,4,6,8,10,12,14,16,18};
int b[9]={3,1,5,9,4,2,7,6,10};
int t[2];
vector<string> splitEx(const string& src, string separate_character)   
{   
    vector<string> strs;   
       
    int separate_characterLen = separate_character.size();//分割字符串的长度,这样就可以支持如“,,”多字符串的分隔符   
    int lastPosition = 0,index = -1;   
    while (-1 != (index = src.find(separate_character,lastPosition)))   
    {   
        strs.push_back(src.substr(lastPosition,index - lastPosition));   
        lastPosition = index + separate_characterLen;   
    }   
    string lastString = src.substr(lastPosition);//截取最后一个分隔符后的内容   
    if (!lastString.empty())   
        strs.push_back(lastString);//如果最后一个分隔符后还有内容就入队   
    return strs;   
}
void main()
{
	int number[7000];
	char num[600000];
	int top;
	ifstream myfile;
	myfile.open("E:\\Documents and Settings\\Administrator\\桌面\\1.txt");
	if(!myfile)
		cout<<"failure"<<endl;
	else
	{
		myfile.getline(num,600000);
		vector<string> strs=splitEx(num," ");
		for(int j=0;j<strs.size();j++)
		{
			number[j]=atoi(strs[j].c_str());
			//cout<<number[j]<<" ";
		}
		//cout<<endl;
		top=strs.size();
		cout<<"一共有"<<top<<"个数。"<<endl;
	}
	int *Max_Min(int *a,int buttom,int top);
	int *tt=Max_Min(number,0,top-1);
	cout<<"最大数为:"<<*(tt+0)<<endl;
	cout<<"最小数为:"<<*(tt+1)<<endl;
}
int *Max_Min(int *a,int buttom,int top)
{
	//停止递归条件
	if((top-buttom)==1)
	{
		
		if(a[top]>a[buttom])
		{
			t[0]=a[top];
			t[1]=a[buttom];
		}
		else
		{
			t[0]=a[buttom];
			t[1]=a[top];
		}
		return t;
	}
	else if(top==buttom)
	{
		t[0]=a[top];
		t[1]=a[buttom];
		return t;
	}
	else
	{


		int middle=(top+buttom)/2;
		int x1=*(Max_Min(a,buttom,middle)+0);
		int x2=*(Max_Min(a,buttom,middle)+1);
		int y1=*(Max_Min(a,middle+1,top)+0);
		int y2=*(Max_Min(a,middle+1,top)+1);
		if(x1<y1)
			t[0]=y1;
		else
			t[0]=x1;
		if(x2<y2)
			t[1]=x2;
		else
			t[1]=y2;
		return t;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值