#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
#include <unordered_set>
#include <queue>
//upper bound >
//lower bound >=
//int index = (lower_bound(testvec.begin(), testvec.end(), num)-testvec.begin());
using namespace std;
using ll = long long;
int mod = 1000000007;
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int n;
cin >> n;
vector<int> startingList;
for (size_t i = 0; i < n; i++)
{
int a;
cin >> a;
startingList.push_back(a);
}
for (size_t i = 0; i < n - 1; i++)
{
if (startingList[n - i - 1] > startingList[n - i - 2]) {
vector<int> ToSort;
int begin = n - i - 2;
for (size_t j = begin; j < n; j++)
{
ToSort.push_back(startingList[j]);
}
sort(ToSort.begin(), ToSort.end());
int index = (upper_bound(ToSort.begin(), ToSort.end(), startingList[begin]) - ToSort.begin());
vector<int> alrSorted;
for (size_t j = 0; j < ToSort.size(); j++)
{
if (j != index) {
alrSorted.push_back(ToSort[j]);
}
}
startingList[begin] = ToSort[index];
for (size_t j = 0; j < alrSorted.size(); j++)
{
startingList[begin + 1 + j] = alrSorted[j];
}
break;
}
}
// Found next iteration, is it correct though?
int max = -1;
int secMax = -1;
int issueIndex = -1;
vector<int> ToSort;
for (int i = startingList.size() - 1; i >= 0; i--)
{
if (startingList[i] > max) {
if (secMax != -1) {
issueIndex = i;
break;
}
else {
max = startingList[i];
}
}
else if (secMax == -1) {
secMax = startingList[i];
}
else if (startingList[i]<secMax) {
max = secMax;
secMax = startingList[i];
}
}
if (issueIndex == -1) {
for (size_t i = 0; i < n; i++)
{
cout << startingList[i] << " ";
}
return 0;
}
for (size_t j = issueIndex + 1; j < n; j++)
{
ToSort.push_back(startingList[j]);
}
sort(ToSort.begin(), ToSort.end());
int largerThanIssueIndex = (upper_bound(ToSort.begin(), ToSort.end(), startingList[issueIndex]) - ToSort.begin());
vector<int> AlrSorted;
for (size_t i = 0; i < largerThanIssueIndex; i++)
{
AlrSorted.push_back(ToSort[largerThanIssueIndex - 1 - i]);
}
for (size_t i = largerThanIssueIndex; i < ToSort.size(); i++)
{
AlrSorted.push_back(ToSort[i]);
}
for (size_t i = issueIndex + 1; i < n; i++)
{
startingList[i] = AlrSorted[i - issueIndex - 1];
}
for (size_t i = 0; i < n; i++)
{
cout << startingList[i] << " ";
}
return 0;
}