较快速在一个数组中查找最大值和最小值(2)
2013-10-13 09:56
483 查看
/*分治法*/ #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; } }
相关文章推荐
- 较快速在一个数组中查找最大值和最小值
- 在一个数组中查找最大的K个元素或者最小的K个元素
- 设计一个最优算法来查找一n个元素数组中的最大值和最小值。已知一种需要比较2n次的方法,请给一个更优的算法。
- 数组 获取最值(最大值 最小值)选择排序 冒泡排序 快速排序 半查找(二分查找) 十进制转其他进制法
- 设计一个最优算法来查找n个元素数组中的最大值和最小值
- 初始化一个有10个整数的数组,在数组中查找并输出最大值和最小值。
- java快速寻找一个数组的最大值或最小值, min, max,三种方法
- 8+查找一个旋转数组的最小元素
- 输入一个递增排序的数组和一个数字S,在数组中查找两个数,是的他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
- 高性能查找数组中的最大值和最小值
- 二维数组, 二分法查找数组元素下标 快速查找数组最大值 数组作为实参的问题
- 用rand函数产生一个数组(长度为100,最小值为99,最大值为999)
- 练习5: 输入一个一维数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
- 输入一个一维数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组
- 查找一个序列的最大值和最小值
- [基础题]1.快速找出一个数组中的最大数、第二大数。
- hdu 5289 Assignment(给一个数组,求有多少个区间,满足区间内的最大值和最小值之差小于k)
- 一个数组中同时找到最大/最小值
- 定义一个int型的一维数组,包含10个元素,分别赋一些随机整数,然后求出所有元素的最大值,最小值,平均值,和值,并输出出来。
- 用递归法求解一个数组中的最大值和最小值的问题