简体   繁体   中英

C++: Finding second max element in array

I am new here and learning C++ language. Right now I have to find the second largest element in the array but my code is not giving me correct output sometimes. I have the following code to find the second max element.

for(int i = 0;i<size;i++)
{
    if(arr[i] > max)
    {
        second_max = max;
        max = arr[i];
    }
}

This code works sometimes and sometimes it doesn't give the correct value of second max element. Please help me what I am doing wrong ?

Assuming that you are finding maximum and the second_maximum elements, what I noticed is that you are skipping the scenario when the arr[i] is greater than the second_max but less than the max eg for the following scenario your code will not work fine

max: 15

second_max = 7

arr[i] = 12

add the following condition to your code below the first if condition:

else if(arr[i] > second_max)
{
    second_max = arr[i];
}

Here's a solution using only standard algorithms:

#include <iostream>
#include <vector>
#include <cassert>

int second_max(std::vector<int> v)
{
    using namespace std;

    sort(begin(v),
         end(v),
         std::greater<>());

    auto last = unique(begin(v),
                       end(v));

    auto size = last - begin(v);

    return (size == 0)
    ? 0
    : (size == 1)
    ? v[0]
    : v[1];
}


int main()
{
    using namespace std;

    cout << second_max({ 3,5,7,7,2,4,3,2,6 }) << endl;
    return 0;
}

Rather than std::sort this should be done with std::nth_element . It's exactly the scenario for it was designed and avoids sorting the entire collection when you only care about a couple of elements.

You can use this little program. I'm using only std's standard algorithms and it's the simplest I can think of.

#include <array>
#include <algorithm>
#include <iostream>

int main()
{
    std::array<int, 10> ar = {1, 5, 15, 2, 3, 5, 6, 8, 9, 14};

    // Sort the array
    std::sort(std::begin(ar), std::end(ar));

    // Print the second max element
    std::cout << ar[ar.size() - 2];
}

The logic of your if-statement is incomplete. Here is the working version:

  for(int i = 0; i<size; i++)
  {
    if(max < arr[i]) {
      second_max = max;
      max = arr[i];
    }
    else if(second_max < arr[i])
      second_max = arr[i];
  }

My solution:

#include <stdio.h>
#include <limits.h>

/**
 * get second max of array
 * @param arr the Array
 * @param len the array length
 * @return return second max if searched otherwise return -1
 */
int getSecondMax(const int *arr, int len) {
    int secondMax = INT_MIN; //-2147483647 - 1
    int max = INT_MIN + 1;
    for (int i = 0; i < len; ++i) {
        if (arr[i] > max) {
            secondMax = max;
            max = arr[i];
        } else if (arr[i] > secondMax && arr[i] != max) {
            secondMax = arr[i];
        }
    }
    return secondMax != INT_MIN + 1 ? secondMax : -1;
}

int main() {
    int arr[] = {0, 3, -1, 4, 5};
    int len = sizeof(arr) / sizeof(arr[0]);

    int secondMax = getSecondMax(arr, len);
    secondMax != -1 ? printf("the second max = %d\n", secondMax) : printf("not found second max\n");
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM