**Given an array of integers, how to find the maximum and minimum?**

Simple solution:

C++:

01 void maxmin(int *A, int size, int& max, int &min)

02 {

03 max=min=A[0];

04 for(int i=1;i<size;i++){

05 if(max<A[i])

06 max=A[i];

07 if(min>A[i])

08 min=A[i];

09 }

10 }

02 {

03 max=min=A[0];

04 for(int i=1;i<size;i++){

05 if(max<A[i])

06 max=A[i];

07 if(min>A[i])

08 min=A[i];

09 }

10 }

Further thought, can we reduce the comparing number? The above approach require 2n comparing in worst case.

Alternative solution:

1.Build n/2 pairs, compare two element for each pair. We can get a max set and min set which composed by the max and min element in each pair.

2.Find the max in the max set and min in the min set.

Number of comparing: n/2+n/2+n/2=3n/2.

Advertisements