Search code examples
c++arraysrecursionmaxdynamic-arrays

Finding maximum values of rests of array


For example:

array[] = {3, 9, 10, **12**,1,4,**7**,2,**6**,***5***}

First, I need maximum value=12 then I need maximum value among the rest of array (1,4,7,2,6,5), so value=7, then maxiumum value of the rest of array 6, then 5, After that, i will need series of this values. This gives back (12,7,6,5).

How to get these numbers? I have tried the following code, but it seems to infinite I think I'll need ​​a recursive function but how can I do this?

max=0; max2=0;...
   for(i=0; i<array_length; i++){

             if (matrix[i] >= max)
                max=matrix[i];

             else {
                  for (j=i; j<array_length; j++){

                      if (matrix[j] >= max2)
                      max2=matrix[j];

                      else{
                       ...
                        ...for if else for if else
                         ...??
                      }
                  }
             }
         }

Solution

  • This is how you would do that in C++11 by using the std::max_element() standard algorithm:

    #include <vector>
    #include <algorithm>
    #include <iostream>
    
    int main()
    {
        int arr[] = {3,5,4,12,1,4,7,2,6,5};
    
        auto m = std::begin(arr);
        while (m != std::end(arr))
        {
            m = std::max_element(m, std::end(arr));
            std::cout << *(m++) << std::endl;
        }
    }
    

    Here is a live example.