+ 3

Write program for find second maximum number.

i want a program for find second maximum number from unsorted array..

26th Mar 2017, 5:14 AM
Mayur Chaudhari
Mayur Chaudhari - avatar
5 Réponses
+ 4
see my codes you will find the solution
26th Mar 2017, 5:28 AM
saqib ali
saqib ali - avatar
+ 3
ok i am search it in your codes.
26th Mar 2017, 5:28 AM
Mayur Chaudhari
Mayur Chaudhari - avatar
+ 3
Your question is pretty general, so here's a generic C++ function I cooked up that should do the trick: template <typename Iter> Iter find_second_largest(Iter begin, Iter end) { Iter max = end; Iter max2 = end; for (Iter i = begin; i != end; ++i) if (max == end || *i > *max) { max2 = max; max = i; } return max2; } Example usage: int main() { std::array<int, 5> arr = { 4, 2, 10, 3, 14 }; // Outputs 10! std::cout << *find_second_largest(arr.begin(), arr.end()); return 0; } In general, what you want to do is keep track of TWO maximum values. Every time you update the max, set the second max to the old value of max. For example, say our current maximum is 10, and we come across 20. Now our current maximum is 20, and our second maximum is 10. Keep doing that as you traverse the collection. Edit: I added a revised version of this function to my code library if you want to play around with it.
26th Mar 2017, 5:56 AM
Squidy
Squidy - avatar
+ 2
thanks @Squidy but your logic is complex to understand.
26th Mar 2017, 5:44 AM
Mayur Chaudhari
Mayur Chaudhari - avatar
+ 1
thanks @saqib ali your program is easy to understand
26th Mar 2017, 5:46 AM
Mayur Chaudhari
Mayur Chaudhari - avatar