分治法解决寻找数组中最大最小值的问题
输入: 数组A[i,…,j]
输出:数组A[i,…,j]中的max和min
1. If j-i+1 =1 Then 输出A[i],A[i],算法结束
2. If j-i+1 =2 Then
3. If A[i]< A[j] Then输出A[i],A[j];算法结束
4. k<--(j-i+1)/2
5. m1,M1<--MaxMin(A[i:k]);
6. m2,M2 <--MaxMin(A[k+1:j]);
7. m <--min(m1,m2);
8. M <--min(M1,M2);
9. 输出m,M
复杂度为3/2n-1
1 #include <iostream> 2 #include <algorithm> 3 using namespace std; 4 5 double num[100]; 6 int n = 0; 7 8 // 用一个结构体来记录最大最小值 9 struct Res 10 { 11 double maxs; 12 double mins; 13 }; 14 15 struct Res MaxAndMin(int left,int right) 16 { 17 Res res,a,b; 18 19 if(left +1 >= right) //判断是否递归到底部 20 { 21 res.maxs = max(num[left],num[right]); 22 res.mins = min(num[left],num[right]); 23 return res; 24 } 25 26 int middle = (right + left) / 2; 27 a = MaxAndMin(left,middle); 28 b = MaxAndMin(middle+1,right); 29 res.maxs = max(a.maxs,b.maxs); 30 res.mins = min(a.mins,b.mins); 31 return res; 32 } 33 int main() 34 { 35 while(cin>>n) 36 { 37 //输入n个数 38 for(int i = 0; i < n; i++) 39 { 40 cin>>num[i]; 41 } 42 43 //只有一个数时,直接输出 44 if(n == 1) 45 { 46 cout<<"最大值:"<<num[0]<<" 最小值:"<<num[0]<<endl; 47 continue; 48 } 49 //只有两个数时,比较这两个数,然后输出 50 if(n == 2) 51 { 52 if(num[0] > num[1]) 53 { 54 cout<<"最大值:"<<num[0]<<" 最小值:"<<num[1]<<endl; 55 } 56 else 57 { 58 cout<<"最大值:"<<num[1]<<" 最小值:"<<num[0]<<endl; 59 } 60 continue; 61 } 62 //多个数时,分治的思想,将数组二分 63 int left = 0,right = n-1; 64 Res result; 65 result = MaxAndMin(left,right); 66 cout<<"最大值:"<<result.maxs<<" 最小值:"<<result.mins<<endl; 67 } 68 69 return 0; 70 }
1 void FindMaxAndMinMethod4(int *pArr, int nStart, int nEnd, int &nMax, int &nMin) 2 { 3 if (nEnd - nStart <= 1) 4 { 5 if (pArr[nStart] > pArr[nEnd]) 6 { 7 nMax = pArr[nStart]; 8 nMin = pArr[nEnd]; 9 } 10 else 11 { 12 nMax = pArr[nEnd]; 13 nMin = pArr[nStart]; 14 } 15 return; 16 } 17 18 int nLeftMax = 0; 19 int nLeftMin = 0; 20 int nRightMax = 0; 21 int nRightMin = 0; 22 FindMaxAndMinMethod4(pArr, nStart, nStart+(nEnd-nStart)/2, nLeftMax, nLeftMin); 23 FindMaxAndMinMethod4(pArr, nStart+(nEnd-nStart)/2+1, nEnd, nRightMax, nRightMin); 24 25 nMax = nLeftMax > nRightMax ? nLeftMax : nRightMax; 26 nMin = nLeftMin < nRightMin ? nLeftMin : nRightMin; 27 }