Finding the 3rd highest value

Can somebody teach me a code on how to find the 3rd highest value.

for example.
At start, the program ask how many loops(or numbers the user wants to add)
User inputs 10 different numbers (0,positive,negative)
Program will try to find out what is the third highest of all.
Sort the numbers..
The function to do that in C++ is called nth_element()

 ``1234567891011121314151617`` ``````#include #include #include #include int main() { std::cout << "Enter 10 different numbers (0, positive, negative) "; std::vector numbers(10); for(size_t n = 0; n < numbers.size(); ++n) std::cin >> numbers[n]; nth_element(numbers.begin(), numbers.begin() + 2, numbers.end(), std::greater()); std::cout << "The 3rd largest number is " << numbers[2] << '\n'; }``````

The algorithm is simple. Let assume that you have an array of n elements int a[n] fiiled with integer numbers.
In the very beginning you set

 ``12`` ``````int max1, max2, max3; max1 = max2 = max3 = a[o];``````

Then in a loop until all elements of the array will be passed you do the following comparisions

 ``123456789101112`` ``````if ( max1 < a[i] ) { max1 = a[i]; max2 = max1; max3 = max2; } else if ( max2 < a[i] ) { max2 = a[i]; max3 = max2; } else if ( max3 < a[i] ) { max3 = a[i]; } ``````
Last edited on
vlad's code won't work. You need to do the assignments in the opposite order. Otherwise you are setting all of the max values to a[i];

 ``123456789101112`` ``````if ( max1 < a[i] ) { max3 = max2; max2 = max1; max1 = a[i]; } else if ( max2 < a[i] ) { max3 = max2; max2 = a[i]; } else if ( max3 < a[i] ) { max3 = a[i]; } ``````
@doug4

 vlad's code won't work. You need to do the assignments in the opposite order

Thanks that you pointed out my typo.
 ``123456789101112131415161718`` ``````for(i=0;i>array[i]; if ( max1 < array[i] ) { max3 = max2; max2 = max1; max1 = array[i]; } else if ( max2 < array[i] ) { max3 = max2; max2 = array[i]; } else if ( max3 < array[i] ) { max3 = array[i]; } }``````
 ``1234567891011121314151617181920`` ``````for(i=0;i>array[i]; } for(i=0;i