首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >较快速在一个数组中查找最大值和最小值(2)

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

作者头像
chain
发布2018-08-02 15:08:46
2.5K0
发布2018-08-02 15:08:46
举报
/*分治法*/
#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;
	}
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2013年10月13日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档