Large to Small Sort in C++


Suppose we have a list of integers nums, we have to sort the list in this manner −

  • First element is maximum

  • Second element is minimum

  • Third element is 2nd maximum

  • Fourth element is 2nd minimum

And so on.

So, if the input is like [6,3,10,4], then the output will be [10, 3, 6, 4]

To solve this, we will follow these steps −

  • Define an array ret

  • sort the array nums

  • j := size of nums - 1

  • i := 0

  • while i <= j, do −

    • insert nums[j] at the end of ret

    • (decrease j by 1)

    • if i <= j, then −

      • insert nums[i] at the end of ret

      • (increase i by 1)

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   vector<int> solve(vector<int> & nums) {
      vector<int> ret;
      sort(nums.begin(), nums.end());
      int j = nums.size() - 1;
      int i = 0;
      while (i <= j) {
         ret.push_back(nums[j]);
         j--;
         if (i <= j) {
            ret.push_back(nums[i]);
            i++;
         }
      }
      return ret;
   }
};
main() {
   Solution ob;
   vector<int> v = {6,3,10,4};
   print_vector(ob.solve(v));
}

Input

{6,3,10,4}

Output

10, 3, 6, 4

Updated on: 02-Sep-2020

490 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements