Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 958
Jacob Avatar asked Sep 11 '09 19:09

Jacob


People also ask

How do you find the largest and second largest number in an array?

We can do it in O(n) or "linear time" meaning as the array gets bigger the number of comparisons grows at the same rate. Loop through the array tracking the max, that's the usual way to find the max. When you find a new max, the old max becomes the 2nd highest number.

How do you find the 2nd largest element in a linked list?

A Simple Solution will be to first sort the linked list in descending order and then print the second element from the sorted linked list. The time complexity of this solution is O(nlogn). A Better Solution is to traverse the Linked list twice. In the first traversal find the maximum element.

How do you find the second largest value?

The simple approach to find second largest element in array can be running two loops. The first loop will find the first largest element in the array. After that, the second loop will find the largest element present in the array which is smaller than first_largest.


3 Answers

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)

like image 92
NomeN Avatar answered Sep 27 '22 21:09

NomeN


using partial_sort ?

std::partial_sort(aTest.begin(), aTest.begin() + 2, aTest.end(), Functor);

An Example:

std::vector<int> aTest;

    aTest.push_back(3);
    aTest.push_back(2);
    aTest.push_back(4);
    aTest.push_back(1);


    std::partial_sort(aTest.begin(), aTest.begin()+2,aTest.end(), std::greater<int>());

    int Max = aTest[0];
int SecMax = aTest[1];
like image 30
aJ. Avatar answered Sep 27 '22 22:09

aJ.


nth_element(begin, begin+n,end,Compare) places the element that would be nth (where "first" is "0th") if the range [begin, end) were sorted at position begin+n and makes sure that everything from [begin,begin+n) would appear before the nth element in the sorted list. So the code you want is:

nth_element(container.begin(),
            container.begin()+1,
            container.end(),
            appropriateCompare);

This will work well in your case, since you're only looking for the two largest. Assuming your appropriateCompare sorts things from largest to smallest, the second largest element with be at position 1 and the largest will be at position 0.

like image 38
Dan Hook Avatar answered Sep 27 '22 21:09

Dan Hook