c++sortingstlrankingvisual-c++-2005

Find largest and second largest element in a range


How do I find the above without removing the largest element and searching again? Is there a more efficient way to do this? It does not matter if the these elements are duplicates.


Solution

  • for (e: all elements) {
     if (e > largest) {
       second = largest;
       largest = e;
     } else if (e > second) {
       second = e;
     }
    }
    

    You could either initialize largest and second to an appropriate lower bound, or to the first two items in the list (check which one is bigger, and don't forget to check if the list has at least two items)