+ 1

How do you find second highest number in an integer array?

U Can provide answer in any language!!!!

18th Jul 2017, 4:40 PM
SREEHARI.M.S.
SREEHARI.M.S. - avatar
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.
18th Jul 2017, 5:04 PM
Hatsy Rei
Hatsy Rei - avatar
18th Jul 2017, 9:51 PM
James
James - avatar
+ 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
18th Jul 2017, 9:56 PM
clement
clement - avatar
+ 1
thanks~~~
19th Jul 2017, 9:52 AM
SREEHARI.M.S.
SREEHARI.M.S. - avatar