C++: Largest first

Sort a list from largest to smallest.

What to build

A one-line sort with a compare object.

Requirements

  • Read the numbers.
  • Print them from largest to smallest, separated by single spaces.

Input

The first line has n. The second line has n whole numbers.

Output

One line.

Constraints

n is from 1 to 1000.

Example

Input:

3
1 3 2

Output:

3 2 1

Why it works

sort accepts a third argument saying how to compare, and greater<int>() reverses the usual order.

Examples

Example 1 · Input
3
1 3 2
Expected output
3 2 1
Example 2 · Input
1
5
Expected output
5

Hints

Hint 1

greater<int>() makes sort go from largest to smallest.

Hint 2

Include <functional> or <algorithm>.

Solution

Show one correct solution (try it yourself first)
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> v(n);
    for (int& x : v) cin >> x;
    sort(v.begin(), v.end(), greater<int>());
    for (int x : v) cout << x << " ";
    cout << endl;
    return 0;
}

Lesson: Iterators and algorithms →