# Given a list number how to get min or max?

This topic is 4662 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Are there available algorithm for it? STL? or .......

##### Share on other sites
Assuming you mean "Given a list of numbers, how do you find the minimum or maximum value", you can use the std::min_element and std::max_element functions, which are defined in <algorithm>.

##### Share on other sites
huh?

a list number?

well if you have an array of numbers you can loop through the array and compare each number til you get to the end (assuming it's a small array < 1000).

##### Share on other sites
Quote:
 Original post by Alpha_ProgDeshuh?a list number?well if you have an array of numbers you can loop through the array and compare each number til you get to the end (assuming it's a small array < 1000).

could you give psesudo code or c++ code for it? thanks

##### Share on other sites
array list = <insert list>var max = list[0]for (n in list) {   if n > max      max = n}

##### Share on other sites
The prefferred C++ way:Array:int array[SIZE];int min = std::min_element( array, array+SIZE );int max = std::max_element( array, array+SIZE );Vector:std::vector<int> vec;int min = std::min_element( vec.begin(), vec.end() );int max = std::max_element( vec.begin(), vec.end() );The manual way:Array:int array[SIZE];int min = array[0];int max = array[0];for( int i=0; i<SIZE; i++ ){    if( min > array )        min = array;    if( max < array )        max = array;}Vector:std::vector<int> vec;int min = vec[0];int max = vec[0];for( int i=0; i<vec.size(); i++ ){    if( min > array )        min = array;    if( max < array )        max = array;}

##### Share on other sites
if you are calculating the biggest/smallest number from an array then you can use sorting algorithms

in my opinion it is best to use sort() function that is in <algorithms.h>
it choses for you the best algorithm to use at a time and is very simple to inplement

or if you don't want to sort the whole array you can use something like this:

maxNumber = array[0];

for(i=1; i<n; ++i)
{
maxNumber = max(array, maxNumber);
};

1. 1
2. 2
Rutin
18
3. 3
4. 4
5. 5

• 12
• 14
• 9
• 9
• 9
• ### Forum Statistics

• Total Topics
632925
• Total Posts
3009237
• ### Who's Online (See full list)

There are no registered users currently online

×