实现求数组的最大值最小值,蛮力法要容易的多。本着重在体验分治法的思想的原则:
1 int main(void) 2 { 3 void Maxmin(int a[],int low,int high,int maxmin[2]); 4 int a[10],maxmin[2]; 5 6 printf("Enter 10 integer numbers:\n"); 7 for(int i=0;i<10;i++) 8 scanf("%d",a+i); 9 10 Maxmin(a,0,9,maxmin); 11 printf("\nMaximum: %d\nMinimum: %d\n",maxmin[0],maxmin[1]); 12 system("pause"); 13 return 1; 14 } 15 16 // 分治法求数组的最大值和最小值 17 void Maxmin(int a[],int low,int high,int maxmin[2]) 18 { 19 int mid; 20 int maxmin1[2],maxmin2[2]; 21 22 if (high==low) 23 { 24 maxmin[0]=a[low]; 25 maxmin[1]=a[low]; 26 return; 27 } 28 if (high==low+1) 29 { 30 if(a[high]>a[low]) 31 { 32 maxmin[0]=a[high]; 33 maxmin[1]=a[low]; 34 }else 35 { 36 maxmin[0]=a[low]; 37 maxmin[1]=a[high]; 38 } 39 return; 40 } 41 else 42 { 43 mid = (high+low)/2; 44 Maxmin(a,low,mid,maxmin1); 45 Maxmin(a,mid+1,high,maxmin2); 46 if(maxmin1[0]>maxmin2[0]) 47 maxmin[0]=maxmin1[0]; 48 else 49 maxmin[0]=maxmin2[0]; 50 // minimum 51 if(maxmin1[1]<maxmin2[1]) 52 maxmin[1]=maxmin1[1]; 53 else 54 maxmin[1]=maxmin2[1]; 55 } 56 }
时间: 2024-10-01 04:34:02