标签:
第二个算法的时间复杂度为O(n),比较次数为3N/2
#include<iostream> #include<vector> #include<ctime> using namespace std; void minmax(vector<int> a){//来自编程珠玑 int min=a[0]; int max=a[0]; int n=a.size(); for(int i=1;i<n;i++){ if(a[i]<min){ min = a[i]; } else if(a[i]>max){ max=a[i]; } } cout<<"min,max="<<min<<","<<max<<endl; } void minmax2(vector<int> a){//来自算法导论 int n = a.size(); int min=a[0]; int max; int k; if(n%2!=0){ max = a[0]; k=1; } else{ max = a[1]; k=2; } for(;k<n;k += 2){ if(a[k]<a[k+1]){ if(a[k]<min){ min = a[k]; } if(a[k+1]>max){ max = a[k+1]; } } else{ if(a[k+1]<min){ min = a[k+1]; } if(a[k]>max){ max = a[k]; } } } cout<<"min,max="<<min<<","<<max<<endl; } int main(){ vector<int> a{12,42,23,3,45,99,21,76}; clock_t st,fi,st2,fi2; st = clock(); minmax(a); fi = clock(); cout<<"minmax:"<<(fi-st)<<endl; st2 = clock(); minmax2(a); fi2 = clock(); cout<<"minmax:"<<(fi2-st2)<<endl; return 0; }
标签:
原文地址:http://www.cnblogs.com/bukekangli/p/4352053.html