Returns the maximum and minimum values of an array.
Calculate the maximum and minimum values of the array. You can traverse the array and record the maximum and minimum values respectively. This method requires 2N comparisons. If you want to reduce the number of comparisons, You can traverse the array, compare Adjacent Elements, and put the greater margin of the adjacent elements behind the smaller ones in front. Select the maximum value from the greater limit to the maximum value of the entire array, and select the minimum value from the smaller value to the minimum value of the entire array. In this case, the number of comparisons is 1.5 * N.
Void findmaxmin (int a [], int n) {if (a = NULL | n <0) return; int I = 0; int maxe = 0x80000000; int mine = 0x7fffffff; for (I = 0; I
A [I + 1]) std: swap (a [I], a [I + 1]);} for (I = 0; I
Maxe) maxe = a [I]; if (a [I]
Maxe) maxe = a [I + 1];} cout <
You can also use the divide and conquer method. First, find the maximum and minimum values in the left half array, then find the maximum and minimum values in the right half array, and then compare the two maximum values to find the maximum value of the entire array, compare the two minimum values to obtain the minimum values of the entire array. Set the number of comparisons to f (n), with f (2) = 1; f (n) = 2 * f (n/2) + 2;
We can find that the number of comparisons is 1.5 * N-2, the number of comparisons is not reduced.
struct res{int min;int max;};res findmaxmin2(int a[],int start,int end){ res r;if(start>=end-1){if(a[start]right.max?left.max:right.max;r.min=left.min