+ 1
How do you find second highest number in an integer array?
U Can provide answer in any language!!!!
4 ответов
+ 10
The first thing which comes to mind would be to extend the normal algorithm for finding the largest number in an array, but to keep track of it's previous number held by the variable which stores the apparent largest integer.
#include <iostream>
int main()
{
int array[5] = {3, 1, 2, 4, 5};
int largest = 0;
int larprev = 0;
for (int i : array)
{
if (i > largest)
{
larprev = largest;
largest = i;
}
else if (i > larprev) larprev = i;
}
std::cout << "Largest : " << largest << std::endl;
std::cout << "Sec largest : " << larprev;
return 0;
}
The second idea would be to just sort the array and get the second last element of the array.
+ 1
Here is JavaScript:
https://code.sololearn.com/WWfEoZ4LDXXI/?ref=app
+ 1
with this you can find the second but not only :)
(it sort the list in another list then return the index you want (allow negative indexes))
https://code.sololearn.com/cyvn20DjsYU1/?ref=app
+ 1
thanks~~~