#include <iostream> using namespace std; #include <assert.h> //分治思想求数组最大最小值 void MaxandMin(int* a,int start,int end,int &Max,int &Min) { if(end-start<=1) { if(a[start] > a[end]) { Max = a[start]; Min = a[end]; } else { Max = a[end]; Min = a[start]; } return; } int RightMax=0; int RightMin=0; int LeftMax=0; int LeftMin=0; MaxandMin(a,start,(start+end)/2,LeftMax,LeftMin); MaxandMin(a,(start+end)/2+1,end,RightMax,RightMin); Max = (RightMax > LeftMax) ? RightMax : LeftMax; Min = (LeftMin < RightMin) ? LeftMin : RightMin; } //暴力方法 void MaxandMin2(int *a,int len,int &max,int &min) { //if(a == NULL || len <= 0) // cout<<"error!"<<endl; assert(len > 0); //if(真) 程序运行;else 报错&&终止程序 max=a[0]; min=a[0]; for(int i(1);i<=len-1;++i) { if(max < a[i]) max = a[i]; if(min > a[i]) min = a[i]; } } // 遍历一遍数组使得下标为偶数的元素较下标为奇数的元素大,再分别求出最大值和最小值 //比较次数为3*N/2次 void MaxandMin3(int *a,int len,int &max,int &min) { if(a == NULL || len<= 0 ) return; for(int i(0);i<len;i+=2) { if(i<len && a[i] < a[i+1]) { int temp = a[i+1]; a[i+1] = a[i]; a[i] = temp; } } max=a[0]; for(int j(2);j<len;j+=2) { if(max < a[j]) { max = a[j]; } } min = a[1]; for(int k(3);k<len;k+=2) { if(min > a[k]) { min = a[k]; } } } // void MaxandMin4(int *a,int len,int &max,int &min) { if(len > 0 && a != NULL) { if(len == 1) { max = min = a[0]; } if(len == 2) { if(a[0] > a[1]) { max = a[0]; min = a[1]; } } // if(a[0] > a[1]) { max = a[0]; min = a[1]; } else { max = a[1]; min = a[0]; } for(int i(2);i<len;i+=2) { if(i+1 < len && a[i] > a[i+1]) { if(max < a[i]) { max = a[i]; } if(min > a[i+1]) { min = a[i+1]; } } else if(i+1 < len && a[i] < a[i+1]) { if(max < a[i+1]) { max = a[i+1]; } if(min > a[i]) { min = a[i]; } } else { if(max < a[i]) { max = a[i]; } if(min > a[i]) { min = a[i]; } } } } } int main() { int a[10]={1,2,3,4,9,8,7,6,5,0}; int max=0; int min =0; MaxandMin(a,0,9,max,min); cout<<"max="<<max<<endl<<"min="<<min<<endl; MaxandMin2(a,10,max,min); cout<<"max="<<max<<endl<<"min="<<min<<endl; MaxandMin3(a,10,max,min); cout<<"max="<<max<<endl<<"min="<<min<<endl; MaxandMin4(a,10,max,min); cout<<"max="<<max<<endl<<"min="<<min<<endl; return 0; }
时间: 2024-10-12 12:02:58