- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements