//* Permutaciones (Forma no recursiva)
//- Importa posición
//- Sin repetición
package permutar3;
import java.util.Arrays;
public class Permutar3 {
public static void main(String[] args) {
int[] perm = {0, 1, 2, 3, 4, 5};
do {
System.out.println(Arrays.toString(perm));
} while (nextPermutation(perm));
}
private static boolean nextPermutation(int[] array) {
int i = array.length - 1;
while (i > 0 && array[i - 1] >= array[i]) {
i--;
}
if (i <= 0) {
return false;
}
int j = array.length - 1;
while (array[j] <= array[i - 1]) {
j--;
}
int temp = array[i - 1];
array[i - 1] = array[j];
array[j] = temp;
j = array.length - 1;
while (i < j) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
return true;
}
}
Resultado:
run:
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 5, 4]
[0, 1, 2, 4, 3, 5]
[0, 1, 2, 4, 5, 3]
[0, 1, 2, 5, 3, 4]
[0, 1, 2, 5, 4, 3]
[0, 1, 3, 2, 4, 5]
[0, 1, 3, 2, 5, 4]
...
...
...
[5, 4, 2, 3, 0, 1]
[5, 4, 2, 3, 1, 0]
[5, 4, 3, 0, 1, 2]
[5, 4, 3, 0, 2, 1]
[5, 4, 3, 1, 0, 2]
[5, 4, 3, 1, 2, 0]
[5, 4, 3, 2, 0, 1]
[5, 4, 3, 2, 1, 0]
BUILD SUCCESSFUL (total time: 0 seconds)