Compares the minimum and maximum values in a dataset.
Minimum and maximum
-- Calculate and import notes
The implementation is so simple that no code implementation is introduced in the computing guide, but the theory is briefly introduced.
The method for finding the maximum and minimum values
Method 1:
void max_min(int* array,int size,int* max){int tmp = 0;for(tmp = 0,*max = array[0];tmp < size;tmp++){*max = *max > array[tmp] ? *max : array[tmp];}}
If the minimum value is the same
It can be found that if the minimum and maximum values need to be found at the same time, 2 * size needs to be compared.
Is there any faster way?
Method 2:
void max_min(int* array,int size,int* min,int* max){int tmp = 0;for(tmp = 0,*min = array[0],array[1];tmp < size;tmp += 2){if(array[tmp] < array[tmp+1]){*min = *min < array[tmp] ? *min : array[tmp];*max = *max > array[tmp+1] ? *max : array[tmp+1];}else{*min = *min < array[tmp+1] ? *min : array[tmp+1];*max = *max > array[tmp] ? *max : array[tmp];}}}
This method reduces the number of comparisons to 3 * size/2 times.
Optimal Algorithms for maximum and minimum values
This is impossible. Consider the three elements a, B, and c.
To find the maximum value, you must compare it twice and then compare it to find the minimum value, while 3*3/2-2 = 2.5
You can also use recursive analysis. Each increase in a number must be compared with the maximum and minimum values of the original array. The number of comparisons increases by 2. Therefore, the number of comparisons is 2n and a constant is added.
Maximum and minimum Algorithms