Returns the maximum and minimum values of an array.
Method 1:
Traverse them once, and the number of times O (2 * n );
Method 2:
According to the book,
Method 3:
It is mainly improved on the basis of method 2. method 2 changes the original array, and method 3 does not change the original array. It defines two variables, Max and min, respectively, to save the maximum and minimum values.
Method 4:
Divide and conquer law, which is the focus.
[CPP]
View plaincopyprint?
- Typedef struct
- {
- Int Max;
- Int min;
- } Ivaluetype;
- Ivaluetype search (int * arr, int M, int N)
- {
- If (n-M <= 1)
- {
- Ivaluetype TMP;
- If (ARR [N]> arr [m])
- {
- TMP. max = arr [N];
- TMP. min = arr [m];
- }
- Else
- {
- TMP. max = arr [m];
- TMP. min = arr [N];
- }
- Return TMP;
- }
- Ivaluetype leftvalue = search (ARR, M, M + (n-M)/2 );
- Ivaluetype rightvalue = search (ARR, M + (n-M)/2 + 1, n );
- Ivaluetype TMP;
- If (leftvalue. max> rightvalue. max)
- TMP. max = leftvalue. Max;
- Else
- TMP. max = rightvalue. Max;
- If (leftvalue. min> rightvalue. min)
- TMP. min = rightvalue. min;
- Else
- TMP. min = leftvalue. min;
- Return TMP;
- }
Complexity 1.5N
For the derivation, see the book: