Compares the minimum and maximum values in a dataset.

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.