There are many solutions to this problem. Assume that the X size of the sequence is N. A common practice is to set the maximum and minimum values to the first element value in the sequence. in a loop, each cycle is updated with the current maximum and minimum to compare, so you need to 2 N-2 times compared; further, if first look for the maximum value, You Need To N-1 times comparison, then look for the minimum value, it requires a N-2 comparison, a total of 2N-3 comparison, 1 less than the previous method. These methods are compared by taking one number each time, and the number of comparisons is O (2N ). Next, we extend the situation to get more than 1 number each time, first try to get 2 number each time, that is, the number of N-2 solution, the number of N to solve. When N = 1, the maximum and minimum values are 1st element values. When N = 2, the maximum and minimum values are the maximum and minimum values of 1st elements and 2nd elements; test X [N-2] and X [N-1], at the same time make the solution of the number of the first N-2 is MAX and MIN, easy to see, do three comparisons can get the new maximum and minimum values, first compare X [N-2] and X [N-1], and then compare the large number with MAX, decimal with MIN, so that about O (3N/2) times to compare, instead of the previous O (2N) times. So, can 3 or 4 numbers be used to further reduce the total number of comparisons? Interestingly, it can be proved that the total number of times required for comparison is the same as the number of two elements. This example shows how to compare two numbers each time. The C ++ code is described as follows:
1 // dynamic array version 1, T must support operator <operation
2 template <typename T>
3 void get_max_min (const T * p, size_t n, T & max, T & min)
4 {
5 assert (n );
6
7 T t_max, t_min, p_min, p_max;
8 p_min = p_max = p [0];
9
10 size_t I;
11 for (I = 1; I <n-1; I + = 2)
12 {
13 if (p [I + 1] <p [I])
14 t_max = p [I], t_min = p [I + 1];
15 else
16 t_max = p [I + 1], t_min = p [I];
17
18 if (p_max <t_max)
19 p_max = t_max;
20
21 if (t_min <p_min)
22 p_min = t_min;
23}
24 if (I = N-1)
25 {
26 if (p_max <p [n-1])
27 p_max = p [n-1];
28 else if (p [n-1] <p_min)
29 p_min = p [n-1];
30}
31 min = p_min; max = p_max;
32}
33
34 // static array version 2, T must support operator <operation
35 template <typename T, size_t N>
36 void get_max_min (const T (& p) [N], T & max, T & min)
37 {
38 get_max_min (p, N, max, min );
39}
For the implementation of the above Code, the previous analysis shows that when N is an odd number, the total number of comparisons is 3/2 * (N-1); when N is an even number, the total number of comparisons is 3N/2-1, and the time complexity is 0 (3N/2 ).