import
java.util.ArrayList;
import
java.util.List;
public
class
SmallestPermutation {
private
static
boolean
check(
int
[] arr,
int
[] new_arr) {
for
(
int
i =
0
; i < arr.length; i++) {
if
(arr[i] == new_arr[i]) {
return
false
;
}
}
return
true
;
}
private
static
void
generatePermutations(
int
[] arr,
int
index, List<Integer> perm,
boolean
[] used, List<
int
[]> permutations) {
if
(index == arr.length) {
int
[] permArray =
new
int
[arr.length];
for
(
int
i =
0
; i < arr.length; i++) {
permArray[i] = perm.get(i);
}
permutations.add(permArray);
return
;
}
for
(
int
i =
0
; i < arr.length; i++) {
if
(!used[i]) {
used[i] =
true
;
perm.add(arr[i]);
generatePermutations(arr, index +
1
, perm, used, permutations);
perm.remove(perm.size() -
1
);
used[i] =
false
;
}
}
}
private
static
void
findSmallestPermutation(
int
[] arr) {
List<
int
[]> permutations =
new
ArrayList<>();
boolean
[] used =
new
boolean
[arr.length];
List<Integer> perm =
new
ArrayList<>();
generatePermutations(arr,
0
, perm, used, permutations);
int
smallestIndex = -
1
;
for
(
int
i =
0
; i < permutations.size(); i++) {
if
(check(arr, permutations.get(i))) {
if
(smallestIndex == -
1
|| compareArrays(permutations.get(i), permutations.get(smallestIndex)) <
0
) {
smallestIndex = i;
}
}
}
if
(smallestIndex == -
1
) {
System.out.println(
"-1"
);
}
else
{
for
(
int
i =
0
; i < arr.length; i++) {
System.out.print(permutations.get(smallestIndex)[i] +
" "
);
}
System.out.println();
}
}
private
static
int
compareArrays(
int
[] arr1,
int
[] arr2) {
int
n = Math.min(arr1.length, arr2.length);
for
(
int
i =
0
; i < n; i++) {
int
cmp = Integer.compare(arr1[i], arr2[i]);
if
(cmp !=
0
) {
return
cmp;
}
}
return
Integer.compare(arr1.length, arr2.length);
}
public
static
void
main(String[] args) {
int
[] arr = {
1
,
2
,
3
,
4
,
5
};
findSmallestPermutation(arr);
}
}