#include <cstdio>
#include <vector>
#include <algorithm>
#include <set>
#include <iterator>

using namespace std;

bool mix = false;

void solve(vector<long> &input_array, set<long> &myset, long lvl) {
	if (myset.empty())
		return;

	long najveci = *--myset.end();
	auto it = find(input_array.rbegin(), input_array.rend(), najveci);
	long index = distance(it, input_array.rend() - 1);

	for (long i = 0; i < input_array.size(); i++) {
		if (najveci == input_array[i] && i == lvl)
			break;
		if (najveci >= input_array[i]) {
			long pom = input_array[i];
			input_array[i] = najveci;
			input_array[index] = pom;
			mix = true;
			return;
		}
	}
	myset.erase(--myset.end());
	return solve(input_array, myset, ++lvl);
}


int main() {
	vector<long> input_array;
	long n;
	scanf("%li", &n);
	for (int i = 0; i < n; i++) {
		long v;
		scanf("%li", &v);
		input_array.push_back(v);
	}
	set<long> myset(input_array.begin(), input_array.end());
	set<long> backup(myset);
	solve(input_array, myset, 0);
	if (!mix) {
		long ubaciti = *backup.begin();
		long pom = input_array[input_array.size() - 2];
		input_array[input_array.size() - 2] = ubaciti;
		input_array[input_array.size() - 1] = pom;
	}
	for (auto x : input_array)
		printf("%li ", x);
	return 0;
}